id
int64
0
25.6k
text
stringlengths
0
4.59k
11,300
calculate the cube of the given number cube is cube is cube is cube is cube is total time taken by threads is creating thread threads in python are an entity within process that can be scheduled for execution in simpler wordsa thread is computation process that is to be performed by computer it is sequence of such instructions within program that can be executed independently of other codes in pythonthere are two ways to create new thread in this articlewe will also be making use of the threading module in python below is detailed list of those processes creating python threads using classbelow has coding example followed by the code explanation for creating new threads using classinpython imprt the threading module import threading class thread(threading thread)def __init__(selfthread_namethread_id)threading thread __init__(selfself thread_name thread_name self thread_id thread_id helper function to execute the threads def run(self)print(str(self thread_name+"str(self thread_id))thread thread("gfg" thread thread("idol" )thread start(thread start(
11,301
outputgfg idol exit creating python threads using functionthe below code shows the creation of new thread using functionexamplefrom threading import thread from time import sleep function to create threads def threaded_function(arg)for in range(arg)print("running"wait sec in between each thread sleep( if __name__ ="__main__"thread thread(target threaded_functionargs ( )thread start(thread join(print("thread finished exiting"outputrunning running running running running running running running running running thread finished exiting so what we did in the above codewe defined function to create thread
11,302
function as its target then we used start(method to start the python thread synchronizing threads the threading module provided with python includes simple-toimplement locking mechanism that allows you to synchronize threads new lock is created by calling the lock(methodwhich returns the new lock the acquire(blockingmethod of the new lock object is used to force threads to run synchronously the optional blocking parameter enables you to control whether the thread waits to acquire the lock if blocking is set to the thread returns immediately with value if the lock cannot be acquired and with if the lock was acquired if blocking is set to the thread blocks and wait for the lock to be released the release(method of the new lock object is used to release the lock when it is no longer required import threading import time class mythread (threading thread)def __init__(selfthreadidnamecounter)threading thread __init__(selfself threadid threadid self name name self counter counter def run(self)print "starting self name get lock to synchronize threads threadlock acquire(print_time(self nameself counter free lock to release next thread threadlock release(def print_time(threadnamedelaycounter)while countertime sleep(delayprint "% % (threadnametime ctime(time time())counter -
11,303
threads [create new threads thread mythread( "thread- " thread mythread( "thread- " start new threads thread start(thread start(add threads to thread list threads append(thread threads append(thread wait for all threads to complete for in threadst join(print "exiting main threadwhen the above code is executedit produces the following result starting thread- starting thread- thread- thu mar : : thread- thu mar : : thread- thu mar : : thread- thu mar : : thread- thu mar : : thread- thu mar : : exiting main thread multithreaded priority queue the queue module is primarily used to manage to process large amounts of data on multiple threads it supports the creation of new queue object that can take distinct number of items the get(and put(methods are used to add or remove items from queue respectively below is the list of operations that are used to manage queueget(it is used to add an item to queue put(it is used to remove an item from queue qsize(it is used to find the number of items in queue empty(it returns boolean value depending upon whether the queue is empty or not
11,304
it returns boolean value depending upon whether the queue is full or not priority queue is an extension of the queue with the following propertiesan element with high priority is dequeued before an element with low priority if two elements have the same prioritythey are served according to their order in the queue below is code example explaining the process of creating multi-threaded priority queueexampleimport queue import threading import time thread_exit_flag class sample_thread (threading thread)def __init__(selfthreadidnameq)threading thread __init__(selfself threadid threadid self name name self def run(self)print ("initializing self nameprocess_data(self nameself qprint ("exiting self namehelper function to process data def process_data(threadnameq)while not thread_exit_flagqueuelock acquire(if not workqueue empty()data get(queuelock release(print (" processing (threadnamedata)elsequeuelock release(time sleep( thread_list ["thread- ""thread- ""thread- "name_list [" "" "" "" "" "
11,305
workqueue queue queue( threads [threadid create new threads for thread_name in thread_listthread sample_thread(threadidthread_nameworkqueuethread start(threads append(threadthreadid + fill the queue queuelock acquire(for items in name_listworkqueue put(itemsqueuelock release(wait for the queue to empty while not workqueue empty()pass notify threads it' time to exit thread_exit_flag wait for all threads to complete for in threadst join(print ("exit main thread"outputinitializing thread- initializing thread- initializing thread- thread- processing athread- processing thread- processing thread- processing thread- processing exiting thread- exiting thread- exiting thread- exit main thread
11,306
multithreading can significantly improve the speed of computation on multiprocessor or multi-core systems because each processor or core handles separate thread concurrently multithreading allows program to remain responsive while one thread waits for inputand another runs gui at the same time this statement holds true for both multiprocessor or single processor systems all the threads of process have access to its global variables if global variable changes in one threadit is visible to other threads as well thread can also have its own local variables disadvantages of multithreadingon single processor systemmultithreading won' hit the speed of computation the performance may downgrade due to the overhead of managing threads synchronization is needed to prevent mutual exclusion while accessing shared resources it directly leads to more memory and cpu utilization multithreading increases the complexity of the programthus also making it difficult to debug it raises the possibility of potential deadlocks it may cause starvation when thread doesn' get regular access to shared resources the application would then fail to resume its work summary in this python multithreading tutorialyou'll get to see different methods to create threads and learn to implement synchronization for thread-safe operations each section of this post includes an example and the sample code to explain the concept step by step by the waymultithreading is core concept of software programming that almost all the high-level programming languages support bibliography
11,307
unit end exercise explain the differences between multithreading and multiprocessing explain different types of multithreading explain different types of thread states explain the wait (and sleep (methods explain different methods for threads****
11,308
module unit structure objectives introduction importing module creating and exploring modules math module random module time module summary bibliography unit end exercise objectives modules are simply 'program logicor 'python scriptthat can be used for variety of applications or functions we can declare functionsclasses etc in module the focus is to break down the code into different modules so that there will be no or minimum dependencies on one another introduction if you quit from the python interpreter and enter it againthe definitions you have made(functions and variablesare lost thereforeif you want to write somewhat longer programyou are better off using text editor to prepare the input for the interpreter and running it with that file as input instead this is known as creating script as your program gets longeryou may want to split it into several files for easier maintenance you may also want to use handy function that you've written in several programs without copying its definition into each program to support thispython has way to put definitions in file and use them in script or in an interactive instance of the interpreter such file is called moduledefinitions from module can be imported into other modules or into the main module (the collection of variables that you have access to in script executed at the top level and in calculator mode
11,309
import in python is similar to #include header_file in / +python modules can get access to code from another module by importing the file/function using import the import statement is the most common way of invoking the import machinerybut it is not the only way import module_namewhen the import is usedit searches for the module initially in the local scope by calling __import__(function the value returned by the function is then reflected in the output of the initial code exampleimport math print(math pioutput import module_name member_namein the above code modulemath is importedand its variables can be accessed by considering it to be class and pi as its object the value of pi is returned by __import__(pi as whole can be imported into our initial coderather than importing the whole module examplefrom math import pi note that in the above examplewe used math pi here we have used pi directly print(pioutput from module_name import in the above code modulemath is not importedrather just pi has been imported as variable all the functions and constants can be imported using
11,310
from math import print(piprint(factorial( )output as said above import uses __import__(to search for the moduleand if not foundit would raise importerror exampleimport mathematics print(mathematics pioutputtraceback (most recent call last)file " :/users/gfg/tuples/xxx py"line in import mathematics importerrorno module named 'mathematics creating and exploring modules what are modules in pythonmodules refer to file containing python statements and definitions file containing python codefor exampleexample pyis called moduleand its module name would be example we use modules to break down large programs into small manageable and organized files furthermoremodules provide reusability of code we can define our most used functions in module and import itinstead of copying their definitions into different programs let us create module type the following and save it as example py python module example def add(ab)"""this program adds two numbers and return the result""result return result
11,311
named example the function takes in two numbers and returns their sum importing moduleswe can import the definitions inside module to another module or the interactive interpreter in python we use the import keyword to do this to import our previously defined module examplewe type the following in the python prompt import example this does not import the names of the functions defined in example directly in the current symbol table it only imports the module name example there using the module name we can access the function using the dot operator for exampleexample add( , python has tons of standard modules you can check out the full list of python standard modules and their use cases these files are in the lib directory inside the location where you installed python standard modules can be imported the same way as we import our user-defined modules executing module as scriptany py file that contains module is essentially also python scriptand there isn' any reason it can' be executed like one here again is mod py as it was defined abovemod py "if comrade napoleon says itit must be right [ def foo(arg)print( 'arg {arg}'class foopass this can be run as scriptc:\users\john\documents>python mod py :\users\john\documentsthere are no errorsso it apparently worked grantedit' not very interesting as it is writtenit only defines objects it doesn' do anything with themand it doesn' generate any output
11,312
some output when run as scriptmod py "if comrade napoleon says itit must be right [ def foo(arg)print( 'arg {arg}'class foopass print(sprint(afoo('quux' foo(print(xnow it should be little more interestingc:\users\john\documents>python mod py if comrade napoleon says itit must be right [ arg quux unfortunatelynow it also generates output when imported as moduleimport mod if comrade napoleon says itit must be right [ arg quux this is probably not what you want it isn' usual for module to generate output when it is imported wouldn' it be nice if you could distinguish between when the file is loaded as module and when it is run as standalone scriptask and ye shall receive when py file is imported as modulepython sets the special dunder variable __name__ to the name of the module howeverif file is run as standalone script__name__ is (creativelyset to the string '__main__using this factyou can discern which is the case at run-time and alter behavior accordinglymod py "if comrade napoleon says itit must be right [ def foo(arg)print( 'arg {arg}'
11,313
pass if (__name__ ='__main__')print('executing as standalone script'print(sprint(afoo('quux' foo(print(xnowif you run as scriptyou get outputc:\users\john\documents>python mod py executing as standalone script if comrade napoleon says itit must be right [ arg quux math module python math module is defined as the most famous mathematical functionswhich includes trigonometric functionsrepresentation functionslogarithmic functionsetc furthermoreit also defines two mathematical constantsi pie and euler numberetc pie ( )it is well-known mathematical constant and defined as the ratio of circumstance to the diameter of circle its value is euler' number( )it is defined as the base of the natural logarithmicand its value is there are different math modules which are given belowmath log (this method returns the natural logarithm of given number it is calculated to the base example html tutorial import math number - small value of of print('log(fabs( )baseis :'math log(math fabs(number) )outputlog(fabs( )baseis - math log (
11,314
called the standard logarithm example import math = small value of of print('log (xis :'math log ( )outputlog (xis math exp(this method returns floating-point number after raising to the given number example import math number - small value of of print('the given number (xis :'numberprint(' ^ (using exp(functionis :'math exp(number)- outputthe given number (xis ^ (using exp(functionis math pow( ,ythis method returns the power of the corresponding to the value of if value of is negative or is not integer value than it raises valueerror example import math number math pow( , print("the power of number:",numberoutputthe power of number math floor(xthis method returns the floor value of the it returns the less than or equal value to exampleimport math number math floor( print("the floor value is:",number
11,315
the floor value is math ceil(xthis method returns the ceil value of the it returns the greater than or equal value to import math number math ceil( print("the floor value is:",numberoutputthe floor value is math fabs(xthis method returns the absolute value of import math number math fabs( print("the floor absolute is:",numberoutputthe absolute value is math factorial(this method returns the factorial of the given number if is not integralit raises valueerror example import math number math factorial( print("the factorial of number:",numberoutputthe factorial of number math modf(xthis method returns the fractional and integer parts of it carries the sign of is float example import math number math modf( print("the modf of number:",numberoutputthe modf of number( python provides the several math modules which can perform the complex task in single-line of code herewe have discussed few important math modules
11,316
the python random module functions depend on pseudorandom number generator function random()which generates the float number between and there are different types of functions used in random module which is given belowrandom random(this function generates random float number between and random randint(this function returns random integer between the specified integers random choice(this function returns randomly selected element from non-empty sequence example hello java program for beginners importing "randommodule import random we are using the choice(function to generate random number fro the given list of numbers print ("the random number from list is ",end=""print (random choice([ ])outputthe random number from list is random shuffle(this function randomly reorders the elements in the list random randrange(beg,end,stepthis function is used to generate number within the range specified in its argument it accepts three argumentsbeginning numberlast numberand stepwhich is used to skip number in the range consider the following example we are using randrange(function to generate in range from to the last parameter is step size to skip ten numbers when selecting import random print (" random number from range is ",end=""print (random randrange( )
11,317
random number from range is random seed(this function is used to apply on the particular random number with the seed argument it returns the mapper value consider the following example importing "randommodule import random using random(to generate random number between and print("the random number between and is "end=""print(random random()using seed(to seed random number random seed( outputthe random number between and is time module python has defined module"timewhich allows us to handle various operations regarding timeits conversions and representationswhich find its use in various applications in life the beginning of time is started measuring from january : am and this very time is termed as "epochin python operations on time time ()this function is used to count the number of seconds elapsed since the epoch gmtime(sec:this function returns structure with values each representing time attribute in sequence it converts seconds into time attributes(daysyearsmonths etc till specified seconds from epoch if no seconds are mentionedtime is calculated till present the structure attribute table is given below index attributes tm_year tm_mon tm_mday tm_hour tm_min tm_sec tm_wday tm_yday tm_isdst values to to to to to ( or are leapseconds to to - where - means library determines dst
11,318
time(and gmtime(importing "timemodule for time operations import time using time(to display time since epoch print ("seconds elapsed since the epoch are ",end=""print (time time()using gmtime(to return the time attribute structure print ("time calculated acc to given seconds is "print (time gmtime()outputseconds elapsed since the epoch are time calculated acc to given seconds is time struct_time(tm_year= tm_mon= tm_mday= tm_hour= tm_min= tm_sec= tm_wday= tm_yday= tm_isdst= asctime("time":this function takes time attributed string produced by gmtime(and returns character string denoting time ctime(sec:this function returns character time string but takes seconds as argument and computes time till mentioned seconds if no argument is passedtime is calculated till present python code to demonstrate the working of asctime(and ctime(importing "timemodule for time operations import time initializing time using gmtime(ti time gmtime(using asctime(to display time acc to time mentioned print ("time calculated using asctime(is ",end=""print (time asctime(ti)using ctime(to display time string using seconds print ("time calculated using ctime(is "end=""print (time ctime()outputtime calculated using asctime(is tue aug : : time calculated using ctime(is tue aug : : sleep(sec:this method is used to halt execution for the time specified in the arguments the program
11,319
python code to demonstrate the working of sleep(importing "timemodule for time operations import time using ctime(to show present time print ("start execution ",end=""print (time ctime()using sleep(to hault execution time sleep( using ctime(to show present time print ("stop execution ",end=""print (time ctime()python python code to demonstrate the working of sleep(importing "timemodule for time operations import time using ctime(to show present time print ("start execution ",end=""print (time ctime()using sleep(to hault execution time sleep( using ctime(to show present time print ("stop execution outputstart execution tue aug : : stop execution tue aug : : summary module is python object with arbitrarily named attributes that you can bind and reference simplya module is file consisting of python code module can define functionsclasses and variables againwe have seen various in-built module like mathtimerandom modules
11,320
explain the concept of module in detail with examples write python code to execute module as script explain the dir function in details what is packagewrite python code to create package of fruit and create two modules apple and orange in it and it contains apple and orange classes respectively create test script py file access both the module in it write short notesastandard module bintra package references cmodule search path bibliography ****
11,321
creating the gui form and adding widgets unit structure objectives introduction widgets label button entry textbox combobox check button radio button scroll bar list box menubutton spin box paned window tk message box summary questions references objectives at the end of this unitthe student will able to design gui form using any widgets like buttonlabelcheckbutton demonstrate the properties of widget learned in introduction in python gui recipes are build using standard built in library of python known as tkinter tkinter is used for creating desktop application steps to install python and environment for tkinter
11,322
must be above to run tkinter properly next download the python ide known as pycharm from the link given- download pycharm community version for trial of days once the download is completerun the exe for install pycharm the setup wizard should have started click next as shown in figure below on the next screenchange the installation path if required click on next as shown in figure below
11,323
click on "next choose the start menu folder keep selected jetbrains and click on "install
11,324
once installation finishedyou should receive message screen that pycharm is installed if you want to go ahead and run itclick the "run pycharm community editionbox first and click finish
11,325
an empty tkinter top-level window can be created by using the following steps import the tkinter module create the main application window add the widgets like labelsbuttonsframes etc to the window call the main event loop so that the actions can take place on the users computer screen
11,326
there are various widgets like buttoncanvascheck buttonentry etc that are used to build the python gui application label label is text used to display some message or information about the other widgets syntax wlabel(master,options list of option are as follows sr no option anchor description it specifies the exact position of the text within the size provided to the widget the default value is centerwhich is used to center the text within the specified space bg the background color displayed behind the widget bitmap it is used to set the bitmap to the graphical object specified so thatthe label can represent the graphics instead of text bd it represents the width of the border the default is pixels cursor the mouse pointer will be changed to the type of the cursor specifiedi arrowdotetc font the font type of the text written inside the widget fg the foreground color of the text written inside the widget height the height of the widget image the image that is to be shown as the label justify it is used to represent the orientation of the text if the text contains multiple lines it can be set to left for left justificationright for right justificationand center for center justification padx the horizontal padding of the text the default value is pady the vertical padding of the text the default value is releif the type of the border the default value is flat text this is set to the string variable which may contain one or more line of text textvariable the text written inside the widget is set to the control variable stringvar so that it can be accessed and changed accordingly
11,327
underline we can display line under the specified letter of the text set this option to the number of the letter under which the line will be displayed width the width of the widget it is specified as the number of characters wraplength instead of having only one line as the label textwe can break it to the number of lines where each line has the number of characters specified to this option codeimport tkinter as tk from tkinter import ttk #create instance win=tk tk(#add title win title("label gui"#adding label ttk label(wintext=" label"grid(column= ,row= #start gui win mainloop(after executing this program on pycharm using run commandthe output of above code as shown below fig label widget button the button widget is used to add various types of buttons to the python application python allows the look of the button according to our requirements various options can be set or reset depending upon the requirements we can also associate method or function with button which is called when the button is pressed syntax =button(parent,options list of possible options is illustrated in table below
11,328
option activebackground activeforeground bd bg command fg font height highlightcolor image justify padx pady relief state underline width wraplength description it represents the background of the button when the mouse hover the button it represents the font color of the button when the mouse hover the button it represents the border width in pixels it represents the background color of the button it is set to the function call which is scheduled when the function is called foreground color of the button the font of the button text the height of the button the height is represented in the number of text lines for the textual lines or the number of pixels for the images the color of the highlight when the button has the focus it is set to the image displayed on the button it illustrates the way by which the multiple text lines are represented it is set to left for left justificationright for the right justificationand center for the center additional padding to the button in the horizontal direction additional padding to the button in the vertical direction it represents the type of the border it can be sunkenraisedgrooveand ridge this option is set to disabled to make the button unresponsive the active represents the active state of the button set this option to make the button text underlined the width of the button it exists as number of letters for textual buttons or pixels for image buttons if the value is set to positive numberthe text lines will be wrapped to fit within this length
11,329
import tkinter as tk from tkinter import ttk #create instance win=tk tk(#adding label that will get modified a_label=ttk label(win,text=" label"a_label grid(column= ,row= #button click event function def click_me()action configure(text="* have been clicked**"a_label configure(foreground='red'a_label configure(text=' red label'#adding button action=ttk button(wintext="click me!",command=click_meaction grid(column= ,row= #start gui win mainloop(here win is the parent of button the output of above code is shown below fig button widget entry textbox the entry widget is used to provide the single line text-box to the user to accept value from the user we can use this widget to accept the text strings from the user it can only be used for one line of text from the user for multiple lines of textwe must use the text widget syntax =entry(parent,options list of possible options is given below sr no option bg bd description the background color of the widget the border width of the widget in pixels
11,330
cursor the mouse pointer will be changed to the cursor type set to the arrowdot etc exportselection the text written inside the entry box will be automatically copied to the clipboard by default we can set the exportselection to to not copy this fg it represents the color of the text font it represents the font type of the text highlightbackground it represents the color to display in the traversal highlight region when the widget does not have the input focus highlightcolor it represents the color to display in the traversal highlight region when the widget does not have the input focus highlightthickness it represents non-negative value indicating the width of the highlight rectangle to draw around the outside of the widget when it has the input focus insertbackground it represents the color to use as background in the area covered by the insertion cursor this color will normally override either the normal background for the widget insertbackground it represents the color to use as background in the are covered by the insertion cursor this color will normally override either the normal background for the widget justify it specifies how the text is orgranized if the text contains multiple lines relief it specifies the type of the border its default value is flat selectbackground the background color of the selected text show it is used to show the entry text of some other type instead of the string for example the password is typed using stars(*textvariable it is set to the instance of the stringvar to retrieve the text from the entry width the width of the displayed text or image xscrollcommand the entry widget can be linked to the horizontal scrollbar if we want the user to enter more text then the actual width of the widget
11,331
import tkinter from tkinter #create win=tk tk(#modified button def action configure(text='hello#changing ttk label(win,text="enter as import tk ttk instance click function click_me()+name get()our label name:"grid(column= ,row= #adding text box entry widget name=tk stringvar(name_entered=ttk entry(win,width= ,textvariable=namename_entered grid(column= ,row= #adding button action=ttk button(win,text="click me",command=click_meaction grid(column= ,row= #start win mainloop(output gui fig text box widget combobox code snippet
11,332
fig output of combobox checkbutton the checkbutton is used to display the checkbutton on the window it is used to track the user' choices provided to the application in other wordswe can say that checkbutton is used to implement the on/off selections the checkbutton can obtain the text or images the checkbutton is mostly used to provide many choices to the user among whichthe user needs to choose the one it generally implements many of many selections syntax =checkbutton(master,options list of possible options is given below sr no option bitmap command highlightcolor justify offvalue onvalue variable width description it displays an image (monochromeon the button it is associated with function to be called when the state of the checkbutton is changed the color of the focus highlight when the checkbutton is under focus this specifies the justification of the text if the text contains multiple lines the associated control variable is set to by default if the button is unchecked we can change the state of an unchecked variable to some other one the associated control variable is set to by default if the button is checked we can change the state of the checked variable to some other one it represents the associated variable that tracks the state of the checkbutton it represents the width of the checkbutton it is represented in the number of characters that are represented in the form of texts
11,333
wraplength if this option is set to an integer numberthe text will be broken in to the number of pieces code snippetoutputfig output of checkbutton radio button the radiobutton is different from checkbutton here the user is provided with various options and the user can select only one option among them it is used to implement one-of-many selection in the python application it shows multiple choices to the user out of whichthe user can select only one out of them we can associate different methods with each of the radiobutton we can display the multiple line text or images on the radiobuttons each button displays single value for that particular variable syntax
11,334
the list of possible options given below sr no option command cursor font fg height highlightcolor state text textvariable value description this option is set to the procedure which must be called every-time when the state of the radiobutton is changed the mouse pointer is changed to the specified cursor type it can be set to the arrowdotetc it represents the font type of the widget text the normal foreground color of the widget text the vertical dimension of the widget it is specified as the number of lines (not pixelit represents the color of the focus highlight when the widget has the focus it represents the state of the radio button the default state of the radiobutton is normal howeverwe can set this to disabled to make the radiobutton unresponsive the text to be displayed on the radiobutton it is of string type that represents the text displayed by the widget the value of each radiobutton is assigned to the control variable when it is turned on by the user code snippet from tkinter import def selection() selection "you selected the option str(radio get() label config(text selection top tk( top geometry(" " radio intvar( lbl label(text "favourite programming language:"
11,335
lbl pack( radiobutton(toptext=" "variable=radiovalue= command=selectionr packanchor radiobutton(toptext=" ++"variable=radiovalue= command=selectionr packanchor radiobutton(toptext="java"variable=radiovalue= command=selectionr packanchor wlabel label(toplabel pack(top mainloop(outputfig output of radiobutton scrollbar it provides the scrollbar to the user so that the user can scroll the window up and down this widget is used to scroll down the content of the other widgets like listboxtext and canvas howeverwe can also create the horizontal scrollbars to the entry widget the syntax to use the scrollbar widget is give below =scrollbar(topoptions list of possible options is given below
11,336
option orient description it can be set to horizontal or vertical depending upon the orientation of the scrollbar jump it is used to control the behavior of the scroll jump if it set to then the callback is called when the user releases the mouse button repeatdelay this option tells the duration up to which the button is to be pressed before the slider starts moving in that direction repeatedly the default is ms takefocus we can tab the focus through this widget by default we can set this option to if we don' want this behavior troughcolor it represents the color of the trough width it represents the width of the scrollbar code snippetfrom tkinter import top tk(sb scrollbar(topsb pack(side rightfill ymylist listbox(topyscrollcommand sb set for line in range( )mylist insert(end"number str(line)mylist packside left sb configcommand mylist yview mainloop(outputfig output of scrollbar
11,337
the listbox widget is used to display list of options to the user it is used to display the list items to the user we can place only text items in the listbox and all text items contain the same font and color the user can choose one or more items from the list depending upon the configuration the syntax to use the listbox is given below =listbox(parent,options list of possible options is given below sr no options selectbackground description the background color that is used to display the selected text selectmode width xscrollcommand yscrollcommand it is used to determine the number of items that can be selected from the list it can set to browsesinglemultipleextended it represents the width of the widget in characters it is used to let the user scroll the listbox horizontally it is used to let the user scroll the listbox vertically code snippetfrom tkinter import top tk(top geometry(" "lbl label(top,text " list of favourite countries "listbox listbox(toplistbox insert( ,"india"listbox insert( "usa"listbox insert( "japan"listbox insert( "austrelia"#this button will delete the selected item from the list btn button(toptext "delete"command lambda listbox=listboxlistb ox delete(anchor)
11,338
listbox pack(btn pack(top mainloop(output fig listbox button output fig after pressing delete button-output menubutton the menubutton is used to display the menu items to the user
11,339
the time it is used to provide the user option to select the appropriate choice exist within the application the menubutton is used to implement various types of menus in the python application menu is associated with the menubutton that can display the choices of the menubutton when clicked by the user the syntax to use the python tkinter menubutton is given below =menubutton(top,options code snippet from tkinter import top tk(top geometry(" "menubutton menubutton(toptext "language"relief flatmenubutton grid(menubutton menu menu(menubuttonmenubutton["menu"]=menubutton menu menubutton menu add_checkbutton(label "hindi"variable=intvar()menubutton menu add_checkbutton(label "english"variable intvar()menubutton pack(top mainloop(output fig output -menubutton
11,340
it is an entry widget used to select from options of values the spinbox widget is an alternative to the entry widget it provides the range of values to the userout of whichthe user can select the one it is used in the case where user is given some fixed number of values to choose from we can use various options with the spinbox to decorate the widget the syntax to use the spinbox is given below syntax =spinbox(topoptions code snippet from tkinter import top tk(top geometry(" "spin spinbox(topfrom_ to spin pack(top mainloop(fig menubutton
11,341
it is like container widget that contains horizontal or vertical panes the panedwindow widget acts like container widget which contains one or more child widgets (panesarranged horizontally or vertically the child panes can be resized by the userby moving the separator lines known as sashes by using the mouse each pane contains only one widget the panedwindow is used to implement the different layouts in the python applications the syntax to use the panedwindow is given below =panedwindow(master,options code snippet from tkinter import def add() int( get() int( get()leftdata str( +bleft insert( ,leftdataw panedwindow( pack(fill bothexpand left entry( bd add(leftw panedwindow( orient verticalw add( entry( entry( add( add( bottom button( text "add"command addw add(bottommainloop(outputfig panedwindow
11,342
this module is used to display the message-box in the desktop based applications the messagebox module is used to display the message boxes in the python applications there are the various functions which are used to display the relevant messages depending upon the application requirements the syntax to use the messagebox is given below messagebox function_name(title,message,[,options] parameter explanation function_name-it represents an appropriate message box functions title-it is string which is shown as title of messagebox message-it is the string to be displayed as message on the massagebox optionsthere are various options which can be used to configure the message dialog box code snippet from tkinter import from tkinter import messagebox top tk(top geometry(" "messagebox askquestion("confirm","are you sure?"top mainloop(outputfig output-tkmessagebox
11,343
in this we discussed about various widgets used in python for handling gui in python programming this also revising the concept of each widget with its syntaxoptionsmethodscode and output in this one section is briefed about installation of pycharm required to handle the python tkinter for gui purpose questions design calculator using widget of python design pendulum clock design pingpong game in tkinter list down the various options of button widget compare and contrast between the listbox and combobox references python gui programming cookbook-burkahard meierpackt publication nd edition useful links ****
11,344
layout management look feel customization unit structure objectives introduction layout management-designing gui application with proper layout management features look feel customizationenhancing look feel of gui using different appearances of widgets summary questions references objectives at the end of this unitthe student will be able to demonstrate the appearance of label widget illustrate how widgets dynamically expand the gui use the grid layout manager describe about the message boxprogress barcanvas widget etc introduction in this we will explore how to manage widgets within widgets to create our python gui learning the fundamentals of gui layout design will enable us to create great-looking gui' there are certain techniques that will help us in achieving this layout design better the grid layout manager is one of the most important layout tools built in to tkinter that will be used in this in this we also going to learn how to customize some of the widgets in our gui by changing some of their properties
11,345
application with proper layout management features arranging several labels within label frame widget the labelframe widget allows us to design our gui in an organized fashion we are still using the grid layout manager as our main layout design toolbut by using labelframe widgetswill get much more control over our gui design pseudocode for labelframe is if we run the above pseudo code the output will simulated as fig output -label frame we can easily align the labels vertically by changing our codeas shown below in pseudocode
11,346
using padding to add space around widgets the procedural way of adding space around widgets is shown here and then use of loop is done to achieve the same thing in much better way buttons_frame grid(column= ,row= ,padx= ,pady= )with this statement labelframe gets some breathing space fig labelframe output in tkinteradding space horizontally and vertically is done by using built-in properties named padx and pady these can be used to add space around many widgetsimproving horizontal and vertical alignmentsrespectively we hardcoded pixels of space to the left and right of labelframeand we added pixels to the top and bottom of the frame now our labelframe stands out better than it did before we can use loop to add space around the labels contained within labelframe
11,347
fig label frame widget with space the grid_configure(function enables us to modify the ui elements before the main loop displays them soinstead of hardcoding values when we first create widgetwe can work on our layout and then arrange spacing towards the end of our filejust before the gui is created the winfo_children(function returns list of all the children belonging to the buttons_frame variable this enables us to loop through them and assign the padding to each label how widgets dynamically expand the gui java introduced the concept of dynamic gui layout management in comparisonvisual development idessuch as vs netlayout the gui in visual manner and basically hardcode the and coordinates of the ui elements using tkinterthis dynamic capability creates both an advantage and little bit of challenge because sometimes our gui dynamically expands when we would rather it not be so dynamic we are using the grid layout manager widget and it lays out our widgets in zero based grid this is very similar to an excel spreadsheet on data base table the following is an example of grid layout manager with two rows and three columns
11,348
row col row col row col row col row col using the grid layout managerwhat happens is that the width of any given column is determined by the longest name or widget in that column this affects all the rows by adding our labelframe widget and giving it title that is longer than some hardcoded size widgetsuch as the top-left label and the text entry below itwe dynamically move those widgets to the center of column adding space on the leftand right-hand side of those widgets the following code can be added to label frame code shown above and then placed labels in to his frame aligning the gui widgets by embedding frames within frames the dynamic behavior of python and its gui modules can create little bit of challenge to really get our gui looking the way we want herewe will embed frames within frames to get more control of our layout this will establish stronger hierarchy among the different ui elementsmaking the visual appearance easier to achieve herewe will create top-level frame that will contain other frames and widgets this will help us get our gui layout just the way we want in order to do sowe will have to embed our current controls within central frame called ttk labelframe this frame ttk labelframe is the child of the main parent window and all controls will be the children of this ttk labelframe we will only assign labelframe to our main window and after thatwe will make this labelframe the parent container for all the widgets fig hierarchy layout in gui
11,349
reference to our main gui tkinter window framemighty is the variable that holds reference to our labelframe and is child of the main window frame (win)and label and all other widgets are now placed into the labelframe container (mightynextwe will modify the following controls to use mighty as the parentreplacing win here is an example of how to do this fig output of above code creating menu bars we will add menu bar to our main windowadd menus to the menu barand then add menu items to the menus we are creating menuitem for functionalities like fileexit and help
11,350
we have to import the menu class from tkinter add the following line of code to the top of the python modulewhere the import statement live as shown below in pseudocode nextwe will create the menu baradd the following code towards the bottom of the modulejust above where we create the main event loop in order to make above code in workable conditionwe also have to add the menu bar and give it label fig menu item with file option nextwe will add second menu item to the first menu that we added to the menu bar
11,351
nextwe will add help functionalities to our existing menu
11,352
nextwe will add menu bar exit functionalities creating tabbed widgets we will create tabbed widgets to further organize our expanding gui written in tkinter pseudocode for same
11,353
using the grid layout manager the grid layout manager is one of the most useful layout tools pseudocode to add grid layout in any python gui code tkinter automatically adds the missing row where we did not specify any particular row look feel customizationenhancing look feel of gui using different appearances of widgets creating message boxes-information warning and error message box is pop-up window that gives feedback to the user it can be informationalhinting at potential problems as well as catastrophic errors using python to create message boxes is very easy add the following line of code to the top of the module where the import statement live nextcreate callback function that will display message box we have to locate the code of the call back above the code where we attach the callback to the menu itembecause this is still procedural and not oop code
11,354
help menu fig help message box nexttransform the above code in to warning message box pop-up windowinstead fig warning message next we will add error message code to show error message box
11,355
how to create independent message boxes we will create out tkinter message boxes as stand-alone top-level gui windows sowhy would we wish to create an independent message boxone reason is that we might customize our message boxes and reuse them in several of our guis instead of having to copy and paste the same code in to every python gui we design fig undesired output of message box we still need title and we definitely want to get rid of this unnecessary second window the second window is caused by windows event loop we can get rid of it by suppressing it
11,356
in code how to create the title of tkinter window form the principle of changing the title of tkinter main root window is the same as what discussed in topic presented above here we create the main root window and give it title fig gui title changing the icon of the main root window we will use an icon that ships with python but you can use any icon you find useful place the following code somewher above the main event loop fig icon added to the main root window
11,357
we will use spinbox widget and we will also bind the enter key on the keyboard to one of our widget we will use tabbed gui code and will add further spinbox widget above the scrolledtext control this simply requires us to increment the scrolledtext row value by one and to insert our new spinbox control in the row above the entry widget firstwe add the spinbox control place the following code above the scrolledtext widget fig spinbox control nextwe will reduce the sixe of the spinbox widgetby adding following code snippet spin=spinbox(mightyfrom= ,to= ,width= fig spin box control with reduce size
11,358
short-hand notation for the borderwidth property spin=spinbox(mightyfrom= to= ,width- bd= fig spin box with border herewe add functionality to the widget by creating callback and linking it to the control fig spinbox with small borderwidth instead of using rangewe can also specify set of values
11,359
reliefsunken and raised appearance of widgets we can control the appearance of our spinbox widgets by using property that makes them appear in different sunken or raised formats we will add one more spinbox control to demonstrate the available appearance of widgets using the relief property of the spinbox control fig two sunken spinbox
11,360
tk sunken tk raised tk flat tk groove tk ridge by assigning the different available options to the relief propertywe can create different appearances for this widget assigning the tk ridge relief and reducing the border width to the same value as our first spinbox widget results in the following gui fig spinbox with two ridge creating tooltips using python we will be adding more useful functionality to our gui surprisinglyadding tooltip to our controls should be simplebut it is not as simple as we would wish it to be in order to achieve this desired functionalitywe will place our tooltip code in to its own oop class
11,361
new class in our python module python allows us to place more than one class in to same pyhton module and it also enables us to mix-and-match classes and regular functions in the same module in our tooltip codewe declare python class and explicitly make it inherit from objectwhich is the foundation of all python classes we can also leave it outas we did in the aclass code examplebecause it is the default for all python classes after all the necessary tooltip creation code that occirs within the tooltip classwe switch over to non-oop python programming by creating function just below it we can add tooltip for our spinbox widgetas follows #add tooltip create_tooltip(spin'this is spin control'we could do the same for all of our other gui widgets in the very same manner we just have to pass in reference to the widget we wish to have tooltipdisplaying some extra information for our scrolledtext widgetwe made the scrol variable point to itso this is what we pass into the constructor of our tooltip creation function
11,362
adding progressbar to the gui progressbar is typically used to show the current status of longrunning process add four buttons in to label frame and set the label frame text property to progressbar we connect each of our four new buttons to new callback functionwhich we assign to their command property
11,363
how to use the canvas widgetfirstwe will create third tab in our gui in order to isolate our new code here is the code to create the new third tab nextwe use another built-in widget of tkinter:canvas lot of people like this widget as it has powerful capabilities
11,364
summary in this we discuss how to add messageboxtooltipprogress bargrid layout and other layout management and customized gui features codes for every widget is covered with output questions design calculator with proper grid layout change the title of main screen write small code for that discuss how to change the border width of the spin box difference between spinbox and combo box create menu driven program for multiplication and division using menu bar additionsubstraction references python gui programming cookbook -burkahard meierpackt publication nd edition ****
11,365
storing data in our mysql database via our gui unit structure objectives introduction connecting to mysql database from python configuring the mysql connectiondesigning the python gui database using the insert command using the update command using the delete command storing and retrieving data from mysql database summary questions references objectives at the end of this unitthe learner will be able to demonstrate the steps for connecting python code to mysql implement the insert command implement the update command implement the delete command introduction before we can connect to mysql serverwe have to have access to mysql server the first thing in this will show you how to install the free mysql server community edition after successfully connecting to running instance of our mysql serverwe will design and create database that will accept book titlewhich could be our own journal or quote we found somewhere on the internet we will require page number for the bookwhich could be blankand then we will insert the quote we like from bookjournalwebsite or friend into our mysql database using our gui built in python we will insertmodifydelete and display our favorite quotes using our python gui to issue these sql commands and to display the data
11,366
four basic sql commands and stands for create readupdateand delete connecting to mysql database from python before we can connect to mysql databasewe have to connect to the mysql server in order to do thiswe need to know the ip address of the mysql server as well as the port it is listening on we also have to be registered user with password in order to get authenticated by the mysql server you will need to have access to running mysql server instance and you also need to have administrator privileges in order to create databases and tables there is free mysql community edition available from the official mysql website you can download and install it on your local pc from :ttp://dev mysql com/downloads in order to connect to mysqlwe first need to install special python connector driver this driver will enable us to talk to the mysql server from python the driver is freely available on the mysql website and comes with very nice online tutorial you can install it from there is currently little bit of surprise at the end of the installation process when we start the msi installer we briefly see messagebox showing the progress of the installationbut then it disappears we get no confirmation that the installation actually succeeded one way to verify that we installed the correct driverthat lets python talk to mysqlis by looking into the python site-packages directory if your site-packages directory looks similar to the following screenshot and you see some new files that havemysql_connector_python in their namewellthen we did indeed install something the official mysql website mentioned above comes with tutorialat the following url: import mysql connector as mysql conn mysql connect(user=password=host= 'print(connconn close(
11,367
the consolethen we are good if you are not able to connect to the mysql serverthen something probably went wrong during the installation if this is the casetry uninstalling mysqlreboot your pcand then run the mysql installation again double-check that you downloaded the mysql installer to match your version of python if you have more than one version of python installedthat sometimes leads to confusion as the one you installed last gets prepended to the windows path environmental variable and some installers just use the first python version they can find in this location in order to connect our gui to mysql serverwe need to be able to connect to the server with administrative privileges if we want to create our own database if the database already existsthen we just need the authorization rights to connectinsertupdateand delete data fig place of mysql in drive folder fig after installation of mysql
11,368
designing the python gui database we used the shortest way to connect to mysql server by hardcoding the credentials required for authentication into the connection method while this is fast approach for early developmentwe definitely do not want to expose our mysql server credentials to anybody unless we grant permission to databasestablesviewsand related database commands to specific users much safer way to get authenticated by mysql server is by storing the credentials in configuration filewhich is what we will do in this recipe we will use our configuration file to connect to the mysql server and then create our own database on the mysql server firstwe create dictionary in the same module of thme ysql py code create dictionary to hold connection info dbconfig 'user'use your admin name 'password'use your admin password 'host' 'ip address of localhost nextin the connection methodwe unpack the dictionary values instead of writinga mysql connect('user''password''host' ' we use(**dbconfigwhich does the same as above but is much shorter import mysql connector as mysql unpack dictionary credentials conn mysql connect(
11,369
print(conn this results in the same successful connection to the mysql serverbut the difference is that the connection method no longer exposes any mission-critical information nowplacing the same usernamepassworddatabaseand so on into dictionary in the same python module does not eliminate the risk of having the credentials seen by any one per using the code in order to increase database securitywe first move the dictionary into its own python module let' call the new python modulg euidbconfig py we then import this module and unpack the credentialsas we did before import guidbconfig as guiconf unpack dictionary credentials conn mysql connect(**guiconf dbconfigprint(conn now that we know how to connect to mysql and have administrator privilegeswe can create our own database by issuing the following commands guidb 'guidbunpack dictionary credentials conn mysql connect(**guiconf dbcon figcursor conn cursor(trycursor execute("create database {default character set 'utf 'format(guidb)except mysql error as errprint("failed to create db{}format(err)conn close( in order to execute commands to mysqlwe create cursor object from the connection object cursor is usually place in specific row in database tablewhich
11,370
itself we wrap the python code into tary except block and use the built-in error codes of mysql to tell us if anything went wrong we can verify that this block works by executing the database-creating code twice the first timeit will create new database in mysqland the second time it will print out an error message stating that this database already exists we can verify which databases exist by executing the following mysql command using the very same cursor object syntax instead of issuing the create database commandwe create cursor and use it to execute the show database commandthe result of which we fetch and print to the console output import mysql connector as mysql import guidbconfig as guiconf unpack dictionary credentials conn mysql connect(**guiconf dbconfigcursor conn cursor(cursor execute("show databases"print(cursor fetchall()conn close( running this code shows us which databases currently exist in our mysql server instance as we can see from the outputmysql ships with several built-in databasessuch as information_schema and so on we have successfully created our owuidb databasewhich is shown in the output all other databases illustrated come shipped with mysql using the insert command creating new databases import mysql connector #create the connection object myconn mysql connector connect(host "localhost"user "root", asswd "google" #creating the cursor object
11,371
try dbs cur execute("show databases" except myconn rollback( for in cur print( myconn close(output fig already existing output import mysql connector #create the connection object myconn mysql connector connect(host "localhost"user "root", asswd "google" #creating the cursor object cur myconn cursor( try #creating new database cur execute("create database pythondb " #getting the list of all the databases which will now include the new database pythondb dbs cur execute("show databases" except myconn rollback(
11,372
print( myconn close(outputfig created new database creating the table we will create the new table employee we have to mention the database name while establishing the connection object we can create the new table by using the create table statement of sql in our database pythondbthe table employee will have the four columnsi nameidsalaryand department_id initially import mysql connector #create the connection object myconn mysql connector connect(host "localhost"user "root", asswd "google",database "pythondb" #creating the cursor object cur myconn cursor( try #creating table with name employee having four columns na meidsalaryand department id dbs cur execute("create table employee(name varchar( not nulli int( not null primary keysalary float not nulldept_id int not nul )"
11,373
myconn rollback( myconn close(fig output of create table insert operation the insert into statement is used to add record to the table in pythonwe can mention the format specifier (%sin place of values we provide the actual values in the form of tuple in the execute(method of the cursor consider the following example import mysql connector #create the connection object myconn mysql connector connect(host "localhost"user "root", asswd "google",database "pythondb" #creating the cursor object cur myconn cursor( sql "insert into employee(nameidsalarydept_idbranch_namev alues (% % % % % ) #the row values are provided in the form of tuple
11,374
try #inserting the values into the table cur execute(sql,val #commit the transaction myconn commit( except myconn rollback( print(cur rowcount,"record inserted!" myconn close(fig insert operation output insert multiple rows we can also insert multiple rows at once using the python script the multiple rows are mentioned as the list of various tuples each element of the list is treated as one particular rowwhereas each element of the tuple is treated as one particular column value (attributeimport mysql connector
11,375
part fundamentals of deep learning what is deep learning before we beginthe mathematical building blocks of neural networks getting started with neural networks fundamentals of machine learning part deep learning in practice deep learning for computer vision deep learning for text and sequences advanced deep-learning best practices generative deep learning conclusions licensed to
11,376
11,377
preface xiii acknowledgments xv about this book xvi about the author xx about the cover xxi part fundamentals of deep learning is deep learning what artificial intelligencemachine learningand deep learning artificial intelligence machine learning learning representations from data the "deepin deep learning understanding how deep learning worksin three figures what deep learning has achieved so far don' believe the short-term hype the promise of ai before deep learninga brief history of machine learning probabilistic modeling early neural networks kernel methods decision treesrandom forestsand gradient boosting machines back to neural networks what makes deep learning different the modern machine-learning landscape vii licensed to
11,378
contents why deep learningwhy now hardware data algorithms new wave of investment the democratization of deep learning will it last we beginthe mathematical building blocks of before neural networks first look at neural network data representations for neural networks scalars ( tensors vectors ( tensors matrices ( tensors tensors and higherdimensional tensors key attributes manipulating tensors in numpy the notion of data batches real-world examples of data tensors vector data timeseries data or sequence data image data video data the gears of neural networkstensor operations element-wise operations broadcasting tensor dot tensor reshaping geometric interpretation of tensor operations geometric interpretation of deep learning the engine of neural networksgradient-based optimization what' derivative derivative of tensor operationthe gradient stochastic gradient descent chaining derivativesthe backpropagation algorithm looking back at our first example summary started with neural networks getting anatomy of neural network layersthe building blocks of deep learning modelsnetworks of layers loss functions and optimizerskeys to configuring the learning process introduction to keras kerastensorflowtheanoand cntk with kerasa quick overview setting up deep-learning workstation developing jupyter notebooksthe preferred way to run deep-learning experiments getting keras runningtwo options licensed to
11,379
contents running deep-learning jobs in the cloudpros and cons what is the best gpu for deep learning classifying movie reviewsa binary classification example the imdb dataset preparing the data building your network validating your approach using trained network to generate predictions on new data further experiments wrapping up classifying newswiresa multiclass classification example the reuters dataset preparing the data building your network validating your approach generating predictions on new data different way to handle the labels and the loss the importance of having sufficiently large intermediate layers further experiments wrapping up predicting house pricesa regression example the boston housing price dataset preparing the data building your network validating your approach using -fold validation wrapping up summary of machine learning fundamentals four branches of machine learning supervised learning unsupervised learning self-supervised learning reinforcement learning evaluating machine-learning models trainingvalidationand test sets keep in mind things to data preprocessingfeature engineeringand feature learning data preprocessing for neural networks engineering overfitting and underfitting feature reducing the network' size adding weight regularization adding dropout the universal workflow of machine learning defining the problem and assembling dataset choosing measure of success deciding on an licensed to
11,380
contents evaluation protocol preparing your data developing model that does better than baseline scaling updeveloping model that overfits regularizing your model and tuning your hyperparameters part summary deep learning in practice learning for computer vision deep introduction to convnets the convolution operation operation the max-pooling training convnet from scratch on small dataset the relevance of deep learning for small-data problems downloading the data building your network data preprocessing using data augmentation using pretrained convnet feature extraction up fine-tuning visualizing what convnets learn wrapping visualizing intermediate activations visualizing convnet filters visualizing heatmaps of class activation summary learning for text and sequences deep working with text data one-hot encoding of words and characters using word embeddings putting it all togetherfrom raw text to word embeddings wrapping up understanding recurrent neural networks recurrent layer in keras understanding the lstm and gru layers concrete lstm example in keras wrapping up advanced use of recurrent neural networks temperature-forecasting problem preparing the data common-sensenon-machine-learning baseline basic machine-learning approach first recurrent baseline using recurrent dropout licensed to
11,381
contents to fight overfitting stacking recurrent layers using bidirectional rnns going even further wrapping up sequence processing with convnets understanding convolution for sequence data pooling for sequence data implementing convnet combining cnns and rnns to process long sequences wrapping up summary deep-learning best practices advanced going beyond the sequential modelthe keras functional api introduction to the functional api multi-input models multi-output models directed acyclic graphs of layers layer weight sharing models as layers wrapping up inspecting and monitoring deep-learning models using keras callbacks and tensorboard using callbacks to act on model during training introduction to tensorboardthe tensorflow visualization framework wrapping up getting the most out of your models advanced architecture patterns hyperparameter optimization model ensembling wrapping up summary deep learning generative text generation with lstm brief history of generative recurrent networks how do you generate sequence data the importance of the sampling strategy implementing character-level lstm text generation wrapping up deepdream implementing deepdream in keras neural style transfer wrapping up the content loss the style loss neural style transfer in keras wrapping up licensed to
11,382
contents generating images with variational autoencoders sampling from latent spaces of images concept vectors for image editing variational autoencoders wrapping up introduction to generative adversarial networks schematic gan implementation bag of tricks the generator the discriminator the adversarial network how to train your dcgan wrapping up summary conclusions key concepts in review various approaches to ai what makes deep learning special within the field of machine learning how to think about deep learning key enabling technologies the universal machine-learning workflow key network architectures the space of possibilities the limitations of deep learning the risk of anthropomorphizing machine-learning models local generalization vs extreme generalization wrapping up the future of deep learning models as programs beyond backpropagation and differentiable layers automated machine learning lifelong learning and modular subroutine reuse the long-term vision staying up to date in fast-moving field practice on real-world problems using kaggle read about the latest developments on arxiv explore the keras ecosystem appendix appendix final words installing keras and its dependencies on ubuntu running jupyter notebooks on an ec gpu instance index licensed to
11,383
if you've picked up this bookyou're probably aware of the extraordinary progress that deep learning has represented for the field of artificial intelligence in the recent past in mere five yearswe've gone from near-unusable image recognition and speech transcriptionto superhuman performance on these tasks the consequences of this sudden progress extend to almost every industry but in order to begin deploying deep-learning technology to every problem that it could solvewe need to make it accessible to as many people as possibleincluding nonexperts--people who aren' researchers or graduate students for deep learning to reach its full potentialwe need to radically democratize it when released the first version of the keras deep-learning framework in march the democratization of ai wasn' what had in mind had been doing research in machine learning for several yearsand had built keras to help me with my own experiments but throughout and tens of thousands of new people entered the field of deep learningmany of them picked up keras because it was--and still is--the easiest framework to get started with as watched scores of newcomers use keras in unexpectedpowerful waysi came to care deeply about the accessibility and democratization of ai realized that the further we spread these technologiesthe more useful and valuable they become accessibility quickly became an explicit goal in the development of kerasand over few short yearsthe keras developer community has made fantastic achievements on this front we've put deep learning into the hands of tens of thousands of peoplewho in turn are using it to solve important problems we didn' even know existed until recently the book you're holding is another step on the way to making deep learning available to as many people as possible keras had always needed companion course to xiii licensed to
11,384
preface simultaneously cover fundamentals of deep learningkeras usage patternsand deeplearning best practices this book is my best effort to produce such course wrote it with focus on making the concepts behind deep learningand their implementationas approachable as possible doing so didn' require me to dumb down anything-- strongly believe that there are no difficult ideas in deep learning hope you'll find this book valuable and that it will enable you to begin building intelligent applications and solve the problems that matter to you licensed to
11,385
' like to thank the keras community for making this book possible keras has grown to have hundreds of open source contributors and more than , users your contributions and feedback have turned keras into what it is today ' also like to thank google for backing the keras project it has been fantastic to see keras adopted as tensorflow' high-level api smooth integration between keras and tensorflow greatly benefits both tensorflow users and keras users and makes deep learning accessible to most want to thank the people at manning who made this book possiblepublisher marjan bace and everyone on the editorial and production teamsincluding christina taylorjanet vailtiffany taylorkatie tennantdottie marsicoand many others who worked behind the scenes many thanks go to the technical peer reviewers led by aleksandar dragosavljevic -diego acuna rozasgeoff bartodavid blumenthal-barbyabel brownclark dormanclark gaylordthomas heimanwilson marsumit palvladimir pasmangustavo patinopeter rabinovitchalvin rajclaudio rodriguezsrdjan santicrichard tobiasmartin verzilliwilliam wheelerand daniel williams--and the forum contributors their contributions included catching technical mistakeserrors in terminologyand typosand making topic suggestions each pass through the review process and each piece of feedback implemented through the forum topics shaped and molded the manuscript on the technical sidespecial thanks go to jerry gaineswho served as the book' technical editorand alex ott and richard tobiaswho served as the book' technical proofreaders they're the best technical editors could have hoped for finallyi' like to express my gratitude to my wife maria for being extremely supportive throughout the development of keras and the writing of this book xv licensed to
11,386
this book was written for anyone who wishes to explore deep learning from scratch or broaden their understanding of deep learning whether you're practicing machine-learning engineera software developeror college studentyou'll find value in these pages this book offers practicalhands-on exploration of deep learning it avoids mathematical notationpreferring instead to explain quantitative concepts via code snippets and to build practical intuition about the core ideas of machine learning and deep learning you'll learn from more than code examples that include detailed commentarypractical recommendationsand simple high-level explanations of everything you need to know to start using deep learning to solve concrete problems the code examples use the python deep-learning framework keraswith tensorflow as backend engine kerasone of the most popular and fastest-growing deeplearning frameworksis widely recommended as the best tool to get started with deep learning after reading this bookyou'll have solid understand of what deep learning iswhen it' applicableand what its limitations are you'll be familiar with the standard workflow for approaching and solving machine-learning problemsand you'll know how to address commonly encountered issues you'll be able to use keras to tackle real-world problems ranging from computer vision to natural-language processingimage classificationtimeseries forecastingsentiment analysisimage and text generationand more xvi licensed to
11,387
xvii who should read this book this book is written for people with python programming experience who want to get started with machine learning and deep learning but this book can also be valuable to many different types of readersif you're data scientist familiar with machine learningthis book will provide you with solidpractical introduction to deep learningthe fastest-growing and most significant subfield of machine learning if you're deep-learning expert looking to get started with the keras frameworkyou'll find this book to be the best keras crash course available if you're graduate student studying deep learning in formal settingyou'll find this book to be practical complement to your educationhelping you build intuition around the behavior of deep neural networks and familiarizing you with key best practices even technically minded people who don' code regularly will find this book useful as an introduction to both basic and advanced deep-learning concepts in order to use kerasyou'll need reasonable python proficiency additionallyfamiliarity with the numpy library will be helpfulalthough it isn' required you don' need previous experience with machine learning or deep learningthis book covers from scratch all the necessary basics you don' need an advanced mathematics backgroundeither--high school-level mathematics should suffice in order to follow along roadmap this book is structured in two parts if you have no prior experience with machine learningi strongly recommend that you complete part before approaching part we'll start with simple examplesand as the book goes onwe'll get increasingly close to state-of-the-art techniques part is high-level introduction to deep learningproviding context and definitionsand explaining all the notions required to get started with machine learning and neural networks presents essential context and background knowledge around aimachine learningand deep learning introduces fundamental concepts necessary in order to approach deep learningtensorstensor operationsgradient descentand backpropagation this also features the book' first example of working neural network includes everything you need to get started with neural networksan introduction to kerasour deep-learning framework of choicea guide for setting up your workstationand three foundational code examples with detailed explanations by the end of this you'll be able to train simple neural licensed to
11,388
about this book networks to handle classification and regression tasksand you'll have solid idea of what' happening in the background as you train them explores the canonical machine-learning workflow you'll also learn about common pitfalls and their solutions part takes an in-depth dive into practical applications of deep learning in computer vision and natural-language processing many of the examples introduced in this part can be used as templates to solve problems you'll encounter in the real-world practice of deep learning examines range of practical computer-vision exampleswith focus on image classification gives you practice with techniques for processing sequence datasuch as text and timeseries introduces advanced techniques for building state-of-the-art deeplearning models explains generative modelsdeep-learning models capable of creating images and textwith sometimes surprisingly artistic results is dedicated to consolidating what you've learned throughout the bookas well as opening perspectives on the limitations of deep learning and exploring its probable future softwarehardware requirements all of this book' code examples use the keras deep-learning framework (keras io)which is open source and free to download you'll need access to unix machineit' possible to use windowstoobut don' recommend it appendix walks you through the complete setup also recommend that you have recent nvidia gpu on your machinesuch as titan this isn' requiredbut it will make your experience better by allowing you to run the code examples several times faster see section for more information about setting up deep-learning workstation if you don' have access to local workstation with recent nvidia gpuyou can use cloud environmentinstead in particularyou can use google cloud instances (such as an -standard- instance with an nvidia tesla add-onor amazon web services (awsgpu instances (such as xlarge instanceappendix presents in detail one possible cloud workflow that runs an aws instance via jupyter notebooksaccessible in your browser source code all code examples in this book are available for download as jupyter notebooks from the book' websitewww manning com/books/deep-learning-with-pythonand on github at licensed to
11,389
xix book forum purchase of deep learning with python includes free access to private web forum run by manning publications where you can make comments about the bookask technical questionsand receive help from the author and from other users to access the forumgo to learn more about manning' forums and the rules of conduct at manning com/forums/about manning' commitment to our readers is to provide venue where meaningful dialogue between individual readers and between readers and the author can take place it isn' commitment to any specific amount of participation on the part of the authorwhose contribution to the forum remains voluntary (and unpaidwe suggest you try asking him some challenging questions lest his interest straythe forum and the archives of previous discussions will be accessible from the publisher' website as long as the book is in print licensed to
11,390
francois chollet works on deep learning at google in mountain viewca he is the creator of the keras deep-learning libraryas well as contributor to the tensorflow machinelearning framework he also does deep-learning researchwith focus on computer vision and the application of machine learning to formal reasoning his papers have been published at major conferences in the fieldincluding the conference on computer vision and pattern recognition (cvpr)the conference and workshop on neural information processing systems (nips)the international conference on learning representations (iclr)and others xx licensed to
11,391
the figure on the cover of deep learning with python is captioned "habit of persian lady in the illustration is taken from thomas jefferysa collection of the dresses of different nationsancient and modern (four volumes)londonpublished between and the title page states that these are hand-colored copperplate engravingsheightened with gum arabic thomas jefferys ( - was called "geographer to king george iii he was an english cartographer who was the leading map supplier of his day he engraved and printed maps for government and other official bodies and produced wide range of commercial maps and atlasesespecially of north america his work as map maker sparked an interest in local dress customs of the lands he surveyed and mappedwhich are brilliantly displayed in this collection fascination with faraway lands and travel for pleasure were relatively new phenomena in the late eighteenth centuryand collections such as this one were popularintroducing both the tourist as well as the armchair traveler to the inhabitants of other countries the diversity of the drawings in jefferysvolumes speaks vividly of the uniqueness and individuality of the world' nations some years ago dress codes have changed since thenand the diversity by region and countryso rich at the timehas faded away it' now often hard to tell the inhabitants of one continent from another perhapstrying to view it optimisticallywe've traded cultural and visual diversity for more varied personal life--or more varied and interesting intellectual and technical life at time when it' difficult to tell one computer book from anothermanning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries agobrought back to life by jefferyspictures xxi licensed to
11,392
11,393
fundamentals of deep learning hapters - of this book will give you foundational understanding of what deep learning iswhat it can achieveand how it works it will also make you familiar with the canonical workflow for solving data problems using deep learning if you aren' already highly knowledgeable about deep learningyou should definitely begin by reading part in full before moving on to the practical applications in part licensed to
11,394
11,395
this covers high-level definitions of fundamental concepts timeline of the development of machine learning key factors behind deep learning' rising popularity and future potential in the past few yearsartificial intelligence (aihas been subject of intense media hype machine learningdeep learningand ai come up in countless articlesoften outside of technology-minded publications we're promised future of intelligent chatbotsself-driving carsand virtual assistants-- future sometimes painted in grim light and other times as utopianwhere human jobs will be scarce and most economic activity will be handled by robots or ai agents for future or current practitioner of machine learningit' important to be able to recognize the signal in the noise so that you can tell world-changing developments from overhyped press releases our future is at stakeand it' future in which you have an active role to playafter reading this bookyou'll be one of those who develop the ai agents so let' tackle these questionswhat has deep learning achieved so farhow significant is itwhere are we headed nextshould you believe the hypethis provides essential context around artificial intelligencemachine learningand deep learning licensed to
11,396
what is deep learningartificial intelligencemachine learningand deep learning firstwe need to define clearly what we're talking about when we mention ai what are artificial intelligencemachine learningand deep learning (see figure )how do they relate to each otherartificial intelligence machine learning deep learning figure art ificial int elligencemachine learningand deep learning artificial intelligence artificial intelligence was born in the swhen handful of pioneers from the nascent field of computer science started asking whether computers could be made to "think"-- question whose ramifications we're still exploring today concise definition of the field would be as followsthe effort to automate intellectual tasks normally performed by humans as suchai is general field that encompasses machine learning and deep learningbut that also includes many more approaches that don' involve any learning early chess programsfor instanceonly involved hardcoded rules crafted by programmersand didn' qualify as machine learning for fairly long timemany experts believed that human-level artificial intelligence could be achieved by having programmers handcraft sufficiently large set of explicit rules for manipulating knowledge this approach is known as symbolic aiand it was the dominant paradigm in ai from the to the late it reached its peak popularity during the expert systems boom of the although symbolic ai proved suitable to solve well-definedlogical problemssuch as playing chessit turned out to be intractable to figure out explicit rules for solving more complexfuzzy problemssuch as image classificationspeech recognitionand language translation new approach arose to take symbolic ai' placemachine learning machine learning in victorian englandlady ada lovelace was friend and collaborator of charles babbagethe inventor of the analytical enginethe first-known general-purposemechanical computer although visionary and far ahead of its timethe analytical licensed to
11,397
engine wasn' meant as general-purpose computer when it was designed in the and sbecause the concept of general-purpose computation was yet to be invented it was merely meant as way to use mechanical operations to automate certain computations from the field of mathematical analysis--hencethe name analytical engine in ada lovelace remarked on the invention"the analytical engine has no pretensions whatever to originate anything it can do whatever we know how to order it to perform its province is to assist us in making available what we're already acquainted with this remark was later quoted by ai pioneer alan turing as "lady lovelace' objectionin his landmark paper "computing machinery and intelligence," which introduced the turing test as well as key concepts that would come to shape ai turing was quoting ada lovelace while pondering whether general-purpose computers could be capable of learning and originalityand he came to the conclusion that they could machine learning arises from this questioncould computer go beyond "what we know how to order it to performand learn on its own how to perform specified taskcould computer surprise usrather than programmers crafting data-processing rules by handcould computer automatically learn these rules by looking at datathis question opens the door to new programming paradigm in classical programmingthe paradigm of symbolic aihumans input rules ( programand data to be processed according to these rulesand out come answers (see figure with machine learninghumans input data as well as the answers expected from the dataand out come the rules these rules can then be applied to new data to produce original answers rules data data answers classical programming answers machine learning rules figure machine learninga new programming paradigm machine-learning system is trained rather than explicitly programmed it' presented with many examples relevant to taskand it finds statistical structure in these examples that eventually allows the system to come up with rules for automating the task for instanceif you wished to automate the task of tagging your vacation picturesyou could present machine-learning system with many examples of pictures already tagged by humansand the system would learn statistical rules for associating specific pictures to specific tags turing"computing machinery and intelligence,mind no ( ) - licensed to
11,398
what is deep learningalthough machine learning only started to flourish in the sit has quickly become the most popular and most successful subfield of aia trend driven by the availability of faster hardware and larger datasets machine learning is tightly related to mathematical statisticsbut it differs from statistics in several important ways unlike statisticsmachine learning tends to deal with largecomplex datasets (such as dataset of millions of imageseach consisting of tens of thousands of pixelsfor which classical statistical analysis such as bayesian analysis would be impractical as resultmachine learningand especially deep learningexhibits comparatively little mathematical theory--maybe too little--and is engineering oriented it' hands-on discipline in which ideas are proven empirically more often than theoretically learning representations from data to define deep learning and understand the difference between deep learning and other machine-learning approachesfirst we need some idea of what machinelearning algorithms do just stated that machine learning discovers rules to execute data-processing taskgiven examples of what' expected soto do machine learningwe need three thingsinput data points--for instanceif the task is speech recognitionthese data points could be sound files of people speaking if the task is image taggingthey could be pictures examples of the expected output--in speech-recognition taskthese could be human-generated transcripts of sound files in an image taskexpected outputs could be tags such as "dog,"cat,and so on way to measure whether the algorithm is doing good job--this is necessary in order to determine the distance between the algorithm' current output and its expected output the measurement is used as feedback signal to adjust the way the algorithm works this adjustment step is what we call learning machine-learning model transforms its input data into meaningful outputsa process that is "learnedfrom exposure to known examples of inputs and outputs thereforethe central problem in machine learning and deep learning is to meaningfully transform datain other wordsto learn useful representations of the input data at hand--representations that get us closer to the expected output before we go any furtherwhat' representationat its coreit' different way to look at data--to represent or encode data for instancea color image can be encoded in the rgb format (red-green-blueor in the hsv format (hue-saturation-value)these are two different representations of the same data some tasks that may be difficult with one representation can become easy with another for examplethe task "select all red pixels in the imageis simpler in the rg formatwhereas "make the image less saturatedis simpler in the hsv format machine-learning models are all about finding appropriate representations for their input data--transformations of the data that make it more amenable to the task at handsuch as classification task licensed to
11,399
artificial intelligencemachine learningand deep learning let' make this concrete consider an -axisa -axisand some points represented by their coordinates in the (xysystemas shown in figure as you can seewe have few white points and few black points let' say we want to develop an algorithm that can take the coordinates (xyof point and output whether that point is likely to be black or to be white in this casethe inputs are the coordinates of our points the expected outputs are the colors of our points way to measure whether our algorithm is doing good job could befor instancethe percentage of points that are being correctly classified figure some sample dat what we need here is new representation of our data that cleanly separates the white points from the black points one transformation we could useamong many other possibilitieswould be coordinate changeillustrated in figure raw data coordinate change better representation figure coordinat change in this new coordinate systemthe coordinates of our points can be said to be new representation of our data and it' good onewith this representationthe black/white classification problem can be expressed as simple rule"black points are such that ,or "white points are such that this new representation basically solves the classification problem in this casewe defined the coordinate change by hand but if instead we tried systematically searching for different possible coordinate changesand used as feedback the percentage of points being correctly classifiedthen we would be doing machine learning learningin the context of machine learningdescribes an automatic search process for better representations all machine-learning algorithms consist of automatically finding such transformations that turn data into more-useful representations for given task these operations can be coordinate changesas you just sawor linear projections (which may destroy information)translationsnonlinear operations (such as "select all points such that ")and so on machine-learning algorithms aren' usually creative in licensed to