id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
14,700 | the aalgorithm finds an optimal solution in this example because it gives up on two paths that are getting too long according to the heuristic plus total cost so far of course the optimality of the solution depends on the heuristic and the total cost for instancethe heuristic should be good enough to return as the cost of getting from the goal to the goal the heuristic cannot over-estimate the cost of getting to the goal from the current node the aalgorithm was used to solve problem in the infinite mario ai competition in this competition programmers from around the world were given the task of writing code that would guide mario through programmable version of the nintendo game mario brothers the idea was that machine learning techniques would be employed to teach mario to make good decisions while navigating the game' world instead of using machine learningrobin baumgarten solved the problem of getting mario through the game by implementing the aalgorithm in robin' solution mario makes choices based on the path length so far plus heuristically computed cost to get to the goal the aimplementation solved the problem and was hit on the internet you can read more about robin' solution and how he developed it at aigamedev com/open/interviews/mario-ai minimax revisited in chap tictactoe was presented as demonstration of two dimensional arrays the outline of the minimax algorithm was presented the minimax algorithm is used by computer games to provide computer opponent minimax only applies in two person games of what is called perfect information these are games where everyone can see everything poker is not game of perfect information tic tac toe is game of perfect information the game of tic tac toe is small enough that adults can generally look far enough ahead so they never loseunless they make careless mistake children on the other hand sometimes can' get enoughif you don' have children or younger brothers and sisterssomeday you will understand tic tac toe is also small enough to be solvable by computer the minimax algorithm can play the game to its conclusion to insure that it never losesjust like an adult the game of connect four is bit different in this gameblack and red checkers are dropped down slots in vertically positioned board the board is seven checkers wide by six checkers tall checkers always drop as far down as possible so there are at most seven choices at each turn in the game the goal is to get four of your checkers in rowa columnor on diagonal in fig the computer has won with the four black checkers on the diagonal playing connect four is not as easy as playing tic tac toe with branching factor of approximately seven at each turnthe number of possible boards quickly grows past what can be considered exhaustively in reasonable amount of time in these situations heuristic must be added to the minimax algorithm to cut off the search the algorithm is not repeated here see sect for complete description of the this copy belongs to 'acha |
14,701 | heuristic search fig the connect four game algorithm the base cases for minimax are then modified as follows to incorporate the search cutoff heuristic the current board is win for the computer in that case minimax returns for computer win the current board is win for the human in that case minimax returns - for human win the current board is full in that casesince neither human or computer wonminimax returns the maximum depth has been reached evaluate the board with no more search and report number between - and negative value indicates the human is more likely to win given this board positive value indicates the computer is more likely to win to implement this last base case for the algorithma new depth parameter is passed to the minimax algorithm and possibly some other parameters as well early in game the maximum depth may not be very deep howeverlater in gamewhen less choices are availablethe maximum depth may be deeper increasing the depth of search is the best way to improve the computer' ability to win at games like this good heuristic can also help in earlier stages of the game when deeper search is not possible coming up with good heuristic is challenge the trick is to keep it relatively simple to compute while encouraging moves in some fashion on the board this copy belongs to 'acha |
14,702 | we have developed connect four implementation based on these ideas that runs on standard hardware without any special multiprocessing our version beats all commercially available apps and applications presently available when playing against them your challengeshould you care to take it onis to build better one front-end for this game is available in sect or on the text' website so you can build your own connect four game summary this covered heuristics and how they play part in problems when the search space grows too large for an exhaustive search many problems that would otherwise be unsolvable are solvable when heuristics are applied howeverthe nature of heuristic is that sometimes they work well and other times they may not if heuristic worked every timeit would be called technique and not heuristic we must think carefully about whether heuristic search is really required or not when solving problems choosing the right problem representationdata structureor algorithm is much more important than brute force approach and applying heuristic it may be that problem that seems too big to solve can be reduced to something that can be solved by the right algorithm when there is no such reduction possibleheuristic search may be the answer the search algorithms hill climbingbest firstand aare best remembered by comparing their algorithms to depth first search and breadth first search hill climbing is like depth first search except that heuristic is applied to order the newly added nodes to the stack best first is like breadth first search except that all the nodes on the queue are ordered according to the heuristic it is often implemented with priority queue the aalgorithm is like best first except that the queue is ordered by the sum of the heuristically estimated distance to the goal plus the distance travelled so far the minimax algorithm too uses heuristic when the search space is too large an effective game engine will always search as deep as possiblebut when the search must be cut offa good heuristic will help in estimating the worth of move in the game review questions answer these short answermultiple choiceand true/false questions to test your mastery of the which is fasterdepth first search or breadth first search which searchdepth first or breadth firstmay not complete in some situationswhen could that happen when hill climbingwhat could prevent the algorithm from finding goal nodethis copy belongs to 'acha |
14,703 | heuristic search will the best first search algorithm find an optimal solutionwhy or why not will the aalgorithm find an optimal solutionwhy or why not when would hill climbing be better to use than the aalgorithm what is forward checking and how does that help solve problem describe what happens in the depth first search algorithm when backtracking occurs be specific about how the algorithm behaves at the point when backtracking occurs in sect name game that cannot use the minimax algorithm other than poker what is the best way to insure that minimax behaves as desireda really good heuristic or deeper search programming problems write program that uses the five search algorithms in this to search maze as shown in the examples construct sample mazes by writing text file where each space represents an open location in the maze and each non-space character represents wall in the maze start the maze with the number of rows and columns of the maze on the first two lines of the file assume that you search the maze from top to bottom to find way through it there should be only one entry and one exit from your maze compare and contrast the different algorithms and their performance on your sample mazes be sure to download the maze searching front-end from the text' website so you can visualize your results the architecture for communication between the front-end and your back-end code is provided in the front-end program file write program to solve the knight' tour problem be sure to use heuristic in your search to narrow the search space make sure you can solve the tour quickly for an board draw your solution using turtle graphics write program to solve the -queens problem use forward checking and heuristic to solve the -queens problem for an board for an extra challenge try to solve it for board the program will likely need to run for while ( half hour?to solve this one be sure to use the -queens front-end code provided on the text' website to visualize your result the back-end code you write should follow the architecture presented at the top of the front-end program file write the connect four program to challenge another student' connect four you both must write programs that have pass button flip of coin can determine who goes first the one who goes first should begin by pressing their pass button then you and the other student can flip back and forth while your computer programs compete to keep things movingyour game must make move within or it forfeits you can use the front-end code presented in sect as your frontend you must write the back-end code follow the architecture to communicate with the front-end code presented at the top of the front-end program file for an extra challengewrite the connect four program and beat the program provided by the authors on text website to run the author' code you must have this copy belongs to 'acha |
14,704 | python version and common lisp installed both the front-end code and the author' back-end code must be in the same directory or folder to run the author' version of the program you can get the author' front-end and back-end code from the text' website this copy belongs to 'acha |
14,705 | this documentation was generated from the python documentation available by typing help(intin the python shell in this documentation the variables xyand refer to integers the official python documentation is at operator + - * / // % returns int int int float int int - & | xy << int int int int int >> ~ int int abs(xdivmod(xyfloat(xhex(xint(xoct(xpow(xy[ ]int ( ,rfloat str int str int repr(xstr(xstr str comments returns the sum of and returns the difference of and returns the product of and returns the quotient of divided by returns the integer quotient of divided by returns modulo this is the remainder of dividing by returns the negation of returns the bit-wise and of and returns the bit-wise or of and returns the bit-wise exclusive or of and returns bit-wise shift left of by bits shifting left by bit multiplies by returns bit-wise right shift of by bits returns an integer where each bit in the has been inverted - for all returns the absolute value of returns the quotient and the remainder as tuple returns the float representation of returns hexadecimal representation of as string returns return an octal representation of as string returns to the power modulo if is not specified then it returns to the power returns string representation of returns string representation of (cspringer international publishing switzerland lee and hubbarddata structures and algorithms with pythonundergraduate topics in computer sciencedoi -- this copy belongs to 'acha |
14,706 | this documentation was generated from the python documentation available by typing help(floatin the python shell in this documentation at least one of the variables and refer to floats the official python documentation is at python org/ operator + - * / // returns float float float float float % float abs(xdivmod(xyint ( ,rfloat(xint(xpow(xyrepr(xstr(xfloat int float str str comments returns the sum of and returns the difference of and returns the product of and returns the quotient of divided by returns the quotient of integer division of divided by howeverthe result is still float returns modulo this is the remainder of dividing by returns the absolute value of returns the quotient and the remainder as tuple both and are floatsbut integer division is performed the value is the whole and fractional part of any remainder the value is whole number returns the float representation of returns the floor of as an integer returns to the power returns string representation of returns string representation of (cspringer international publishing switzerland lee and hubbarddata structures and algorithms with pythonundergraduate topics in computer sciencedoi -- this copy belongs to 'acha |
14,707 | methods this documentation was generated from the python documentation available by typing help(strin the python shell in the documentation found here the variables and are references to strings the official python documentation is at python org/ method + in == returns str bool bool >= <= > < != [ibool bool bool bool bool str [[ ]:[ ]str * * chr(ifloat(sint(slen(sord(srepr(sstr(ss capitalize(str str str float int int int str str comments return new string which is the concatenation of and returns true if is substring of and false otherwise returns true if and refer to strings with the same sequence of characters returns true if is lexicographically greater than or equal to returns true if is lexicographically less than or equal to returns true if is lexicographically greater than returns true if is lexicographically less than returns true if is lexicographically not equal to returns the character at index in the string if is negative then it returns the character at index len( )- returns the slice of characters starting at index and extending to index - in the string if is omitted then the slice begins at index if is omitted then the slice extends to the end of the list if is negative then it returns the slice starting at index len(si (and likewise for the slice ending at jreturns new string with repeated times returns new string with repeated times return the ascii character equivalent of the integer returns the float contained in the string returns the integer contained in the string returns the number of characters in returns the ascii decimal equivalent of the single character string returns string representation of this adds an extra pair of quotes to returns string representation of in this case you get just the string returns copy of the string with the first character upper case (continued(cspringer international publishing switzerland lee and hubbarddata structures and algorithms with pythonundergraduate topics in computer sciencedoi -- this copy belongs to 'acha |
14,708 | appendix cstring operators and methods (continuedmethod center(width[fillchar]returns str count(sub[start[end]]int encode([encoding[errors]]bytes endswith(suffix[start[end]]bool expandtabs([tabsize]str find(sub[start[end]]int format(*args**kwargss index(sub[start[end]]str int isalnum(bool isalpha(bool isdecimal(bool isdigit(bool isidentifier(bool islower(bool comments returns centered in string of length width padding is done using the specified fill character (default is spacereturns the number of non-overlapping occurrences of substring sub in string [start:endoptional arguments start and end are interpreted as in slice notation encodes using the codec registered for encoding encoding defaults to the default encoding errors may be given to set different error handling scheme default is 'strictmeaning that encoding errors raise unicodeencodeerror other possible values are 'ignore''replaceand 'xmlcharrefreplaceas well as any other name registered with codecs register_error that can handle unicodeencodeerrors returns true if ends with the specified suffixfalse otherwise with optional starttest beginning at that position with optional endstop comparing at that position suffix can also be tuple of strings to try returns copy of where all tab characters are expanded using spaces if tabsize is not givena tab size of characters is assumed returns the lowest index in where substring sub is foundsuch that sub is contained within [start:endoptional arguments start and end are interpreted as in slice notation return - on failure like find(but raise valueerror when the substring is not found returns true if all characters in are alphanumeric and there is at least one character in sfalse otherwise returns true if all characters in are alphabetic and there is at least one character in sfalse otherwise returns true if there are only decimal characters in sfalse otherwise returns true if all characters in are digits and there is at least one character in sfalse otherwise returns true if is valid identifier according to the language definition returns true if all cased characters in are lowercase and there is at least one cased character in sfalse otherwise (continuedthis copy belongs to 'acha |
14,709 | (continuedmethod isnumeric(returns bool isprintable(bool isspace(bool istitle(bool isupper(bool join(sequencestr ljust(width[fillchar]str lower( lstrip([chars]str str partition(sep( ,sep,ts replace (oldnew[count]str rfind(sub[start[end]]int rindex(sub[start[end]]int rjust(width[fillchar]str rpartition(sep( ,sep, comments returns true if there are only numeric characters in sfalse otherwise returns true if all characters in are considered printable in repr(or is emptyfalse otherwise returns true if all characters in are whitespace and there is at least one character in sfalse otherwise returns true if is titlecased string and there is at least one character in si upperand titlecase characters may only follow uncased characters and lowercase characters only cased ones return false otherwise returns true if all cased characters in are uppercase and there is at least one cased character in sfalse otherwise returns string which is the concatenation of the strings in the sequence the separator between elements is returns left-justified in unicode string of length width padding is done using the specified fill character (default is spacereturns copy of the string converted to lowercase returns copy of the string with leading whitespace removed if chars is given and not noneremove characters in chars instead searches for the separator sep in sand returns the part before itthe separator itselfand the part after it if the separator is not foundreturns and two empty strings returns copy of with all occurrences of substring old replaced by new if the optional argument count is givenonly the first count occurrences are replaced returns the highest index in where substring sub is foundsuch that sub is contained within [start:endoptional arguments start and end are interpreted as in slice notation returns - on failure like rfind(but raise valueerror when the substring is not found returns right-justified in string of length width padding is done using the specified fill character (default is spacesearches for the separator sep in sstarting at the end of sand returns the part before itthe separator itselfand the part after it if the separator is not foundreturns two empty strings and (continuedthis copy belongs to 'acha |
14,710 | appendix cstring operators and methods (continuedmethod rsplit([sep[maxsplit]]returns comments string list returns list of the words in susing sep as the delimiter stringstarting at the end of the string and working to the front if maxsplit is givenat most maxsplit splits are done if sep is not specifiedany whitespace string is separator rstrip([chars]str returns copy of the string with trailing whitespace removed if chars is given and not noneremoves characters in chars instead split([sep[maxsplit]]string list returns list of the words in susing sep as the delimiter string if maxsplit is givenat most maxsplit splits are done if sep is not specified or is noneany whitespace string is separator and empty strings are removed from the result splitlines([keepends]string list returns list of the lines in sbreaking at line boundaries line breaks are not included in the resulting list unless keepends is given and true startswith(prefix[start[end]]bool returns true if starts with the specified prefixfalse otherwise with optional starttest beginning at that position with optional endstop comparing at that position prefix can also be tuple of strings to try strip([chars]str returns copy of the string with leading and trailing whitespace removed if chars is given and not noneremoves characters in chars instead swapcase(str returns copy of with uppercase characters converted to lowercase and vice versa title(str returns titlecased version of si words start with title case charactersall remaining cased characters have lower case translate(tablestr returns copy of the string swhere all characters have been mapped through the given translation tablewhich must be mapping of unicode ordinals to unicode ordinalsstringsor none unmapped characters are left untouched characters mapped to none are deleted upper(str returns copy of converted to uppercase zfill(widthstr pad numeric string with zeros on the leftto fill field of the specified width the string is never truncated this copy belongs to 'acha |
14,711 | methods this documentation was generated from the python documentation available by typing help(listin the python shell in the documentation found here the variables and are references to lists the official python documentation is at method list(returns list list(sequenceitem [,item]list list + list in del [ibool == bool >= bool <= bool > < bool bool != bool [iitem comments returns new empty list you can also use to initialize new empty list returns new list initialized from sequence' items writing number of comma-separated items in square brackets constructs new list of those items returns new list containing the concatenation of the items in and returns true if the item is in and false otherwise deletes the item at index in this is not an expression and does not return value returns true if and contain the same number of items and each of those corresponding items are pairwise equal returns true if is greater than or equal to according to lexicographical ordering of the elements in and if and have different lengths their items are =up to the shortest lengththen this returns true if is longer than returns true if is lexicographically before or equal to and false otherwise returns true if is lexicographically after and false otherwise returns true if is lexicographically before and false otherwise returns true if and are of different length or if some item of is not =to some item of otherwise it returns false returns the item at index of (continued(cspringer international publishing switzerland lee and hubbarddata structures and algorithms with pythonundergraduate topics in computer sciencedoi -- this copy belongs to 'acha |
14,712 | (continuedmethod [[ ]:[ ] appendix dlist operators and methods returns list [ ]= += *= iter(xlen(xx* * repr(xx append(eiterator int list list str none count(ex extend(iterx index( ,[ ,[ ]]int none int insert(iex pop([index]none item remove(enone reverse( sort(none none comments returns the slice of items starting at index and extending to index - in the string if is omitted then the slice begins at index if is omitted then the slice extends to the end of the list if is negative then it returns the slice starting at index len( )+ (and likewise for the slice ending at jassigns the position at index the value of in the list must already have an item at index before this assignment occurs in other wordsassigning an item to list in this way will not extend the length of the list to accommodate it this mutates the list to append the items in this mutates the list to be copies of the original returns an iterator over returns the number of items in returns new list with the items of repeated times returns new list with the items of repeated times returns string representation of this mutates the value of to add as its last element the function returns nonebut the return value is irrelevant since it mutates returns the number of occurrences of in by using =equality mutates by appending elements from the iterableiter returns the first index of an element that = between the the start indexiand the stop indexj- it raises valueerror if the value is not present in the specified sequence if is omitted then it searches to the end of the list if is omitted then it searches from the beginning of the list insert before index in xmutating remove and return the item at index if index is omitted then the item at len( )- is removed the pop method returns the item and mutates it raises indexerror if list is empty or index is out of range remove first occurrence of in xmutating it raises valueerror if the value is not present reverses all the items in xmutating sorts all the items of according to their natural ordering as determined by the item' __cmp__ methodmutating two keyword parameters are possiblekey and reverse if reverse=true is specifiedthen the result of sorting will have the list in reverse of the natural ordering if key= is specified then must be function that takes an item of and returns the value of that item that should be used as the key when sorting this copy belongs to 'acha |
14,713 | methods this documentation was generated from the python documentation available by typing help(dictin the python shell in the documentation found here the variable is reference to dictionary few methods were omitted here for brevity the official python documentation is at method dict(dict(mappingdict(seqreturns dict dict dict dict(**kwargsdict in del [kd == bool [kvalue type iterator int bool iter(dlen(dd != repr(dd[ ]= clear( copy( get( [, ] items(bool str none dict value type items comments new empty dictionary new dictionary initialized from mapping object' (keyvaluepairs new dictionary initialized as if viad {for kv in seqd[kv new dictionary initialized with the name=value pairs in the keyword arg list for exampledict(one= two= true if has key kelse false deletes key from dictionary returns true if dictionaries and have same keys mapped to same values returns value maps to in if is not mappedit raises keyerror exception returns an iterator over returns the number of keys in returns true if and have any different keys or keys map to different values returns string representation of stores the keyvalue pair , in remove all items from shallow copy of [kif in delse defaults to none set-like object providing view on ' items (continued(cspringer international publishing switzerland lee and hubbarddata structures and algorithms with pythonundergraduate topics in computer sciencedoi -- this copy belongs to 'acha |
14,714 | appendix edictionary operators and methods (continuedmethod keys( pop( [, ]returns keys popitem((kvd setdefault( [, ] update( **fd get( ,enone values(values comments set-like object providing view on ' keys remove specified key and return the corresponding value if key is not founde is returned if givenotherwise keyerror is raised remove and return some (keyvaluepair as -tuplebut raise keyerror if is empty returns get( ,eand also sets [ ]= if not in update from dict/iterable and if has keys(methoddoesfor in ed[ke[kif lacks keys(methoddoesfor (kvin ed[kv in either casethis is followed byfor in fd[kf[kan object providing view on ' values this copy belongs to 'acha |
14,715 | this documentation was generated from the python documentation available by typing from turtle import help turtle in the python shell in the documentation found here the variable turtle is reference to turtle object this is subset of that documentation the official python documentation is at method description turtle back(distancealiasesbackward bk argumentdistance number move the turtle backward by distanceopposite to the direction the turtle is headed do not change the turtle' heading example (for turtle instance named turtle)turtle position(( turtle backward( turtle position((- turtle begin_fill(called just before drawing shape to be filled example (for turtle instance named turtle)turtle color("black","red"turtle begin_fill(turtle circle( turtle end_fill((cspringer international publishing switzerland lee and hubbarddata structures and algorithms with pythonundergraduate topics in computer sciencedoi -- this copy belongs to 'acha |
14,716 | appendix fturtle methods method description turtle begin_poly(start recording the vertices of polygon current turtle position is first point of polygon example (for turtle instance named turtle)turtle begin_poly(turtle circle(radiusextent=nonesteps=noneargumentsradius number extent (optionala number steps (optionalan integer draw circle with given radius the center is radius units left of the turtleextent an angle determines which part of the circle is drawn if extent is not givendraw the entire circle if extent is not full circleone endpoint of the arc is the current pen position draw the arc in counterclockwise direction if radius is positiveotherwise in clockwise direction finally the direction of the turtle is changed by the amount of extent as the circle is approximated by an inscribed regular polygonsteps determines the number of steps to use if not givenit will be calculated automatically maybe used to draw regular polygons callcircle(radiusfull circle -orcircle(radiusextentarc -orcircle(radiusextentsteps-orcircle(radiussteps= -sided polygon example (for turtle instance named turtle)turtle circle( turtle circle( semicircle turtle clear(delete the turtle' drawings from the screen do not move turtle state and position of the turtle as well as drawings of other turtles are not affected examples (for turtle instance named turtle)turtle clear(turtle color(*argsargumentsseveral input formats are allowed they use or arguments as followscolor(return the current pencolor and the current fillcolor as pair of color specification strings as are returned by pencolor and fillcolor this copy belongs to 'acha |
14,717 | method description color(colorstring)color(( , , ))color( , ,binputs as in pencolorset bothfillcolor and pencolorto the given value color(colorstring colorstring )color(( , , )( , , )equivalent to pencolor(colorstring and fillcolor(colorstring and analogouslyif the other input format is used if turtleshape is polygonoutline and interior of that polygon is drawn with the newly set colors for mor info seepencolorfillcolor example (for turtle instance named turtle)turtle color('red''green'turtle color(('red''green'colormode( color(( )( )color(('# ''# 'turtle degrees(set the angle measurement units to degrees example (for turtle instance named turtle)turtle heading( turtle degrees(turtle heading( turtle dot(size=none*coloroptional argumentssize an integer +>+ (if givencolor colorstring or numeric color tuple draw circular dot with diameter sizeusing color if size is not giventhe maximum of pensize+ and *pensize is used example (for turtle instance named turtle)turtle dot(turtle fd( )turtle dot( "blue")turtle fd( turtle end_fill(fill the shape drawn after the call begin_fill(example (for turtle instance named turtle)turtle color("black","red"turtle begin_fill(turtle circle( turtle end_fill(this copy belongs to 'acha |
14,718 | appendix fturtle methods method description turtle end_poly(stop recording the vertices of polygon current turtle position is last point of polygon this will be connected with the first point example (for turtle instance named turtle)turtle end_poly(turtle filling(return fillstate (true if fillingfalse elseexample (for turtle instance named turtle)turtle begin_fill(if turtle filling()turtle pensize( elseturtle pensize( turtle fillcolor(*argsreturn or set the fillcolor argumentsfour input formats are allowedfillcolor(return the current fillcolor as color specification stringpossibly in hex-number format (see examplemay be used as input to another color/pencolor/fillcolor call fillcolor(colorstrings is tk color specification stringsuch as "redor "yellowfillcolor((rgb)* tupleof rgand bwhich representan rgb colorand each of rgand are in the range colormodewhere colormode is either or fillcolor(rgbrgand represent an rgb colorand each of rgand are in the range colormode if turtleshape is polygonthe interior of that polygon is drawn with the newly set fillcolor example (for turtle instance named turtle)turtle fillcolor('violet'col turtle pencolor(turtle fillcolor(colturtle fillcolor( turtle forward(distancealiasesfd argumentdistance number (integer or floatthis copy belongs to 'acha |
14,719 | method description move the turtle forward by the specified distancein the direction the turtle is headed example (for turtle instance named turtle)turtle position(( turtle forward( turtle position(( , turtle forward(- turtle position((- , turtle get_poly(return the lastly recorded polygon example (for turtle instance named turtle) turtle get_poly(turtle register_shape("myfavouriteshape"pturtle get_shapepoly(return the current shape polygon as tuple of coordinate pairs examples (for turtle instance named turtle)turtle shape("square"turtle shapetransform( - turtle get_shapepoly((( - )( )(- )(- - )turtle getscreen(return the turtlescreen objectthe turtle is drawing on so turtlescreen-methods can be called for that object example (for turtle instance named turtle)ts turtle getscreen(ts ts bgcolor("pink"turtle goto(xy=nonealiasessetpos setposition argumentsx number or pair/vector of numbers number none callgoto(xytwo coordinates -orgoto((xy) pair (tupleof coordinates -orgoto(vece as returned by pos(move turtle to an absolute position if the pen is downa line will be drawn the turtle' orientation does not change this copy belongs to 'acha |
14,720 | appendix fturtle methods method description example (for turtle instance named turtle)tp turtle pos(tp ( turtle setpos( , turtle pos(( , turtle setpos(( , )turtle pos(( , turtle setpos(tpturtle pos(( , turtle heading(return the turtle' current heading example (for turtle instance named turtle)turtle left( turtle heading( turtle hideturtle(makes the turtle invisible aliasesht it' good idea to do this while you're in the middle of complicated drawingbecause hiding the turtle speeds up the drawing observably example (for turtle instance named turtle)turtle hideturtle(turtle isdown(return true if pen is downfalse if it' up example (for turtle instance named turtle)turtle penup(turtle isdown(false turtle pendown(turtle isdown(true turtle isvisible(return true if the turtle is shownfalse if it' hidden example (for turtle instance named turtle)turtle hideturtle(print(turtle isvisible()false this copy belongs to 'acha |
14,721 | method description turtle left(anglealiaseslt argumentangle number (integer or floatturn turtle left by angle units (units are by default degreesbut can be set via the degrees(and radians(functions angle orientation depends on mode (see this example (for turtle instance named turtle)turtle heading( turtle left( turtle heading( turtle onclick(funbtn= add=nonebind fun to mouse-click event on this turtle on canvas argumentsfun function with two argumentsto which will be assigned the coordinates of the clicked point on the canvas num number of the mouse-button defaults to (left mouse buttonadd true or false if truenew binding will be addedotherwise it will replace former binding example for the anonymous turtlei the procedural waydef turn(xy)turtle left( onclick(turnnow clicking into the turtle will turn it onclick(noneevent-binding will be removed turtle ondrag(funbtn= add=nonebind fun to mouse-move event on this turtle on canvas argumentsfun function with two argumentsto which will be assigned the coordinates of the clicked point on the canvas num number of the mouse-button defaults to (left mouse buttonevery sequence of mouse-move-events on turtle is preceded by mouse-click event on that turtle example (for turtle instance named turtle)turtle ondrag(turtle goto##subsequently clicking and dragging turtle will ##move it across the screen thereby producing handdrawings ##(if pen is downthis copy belongs to 'acha |
14,722 | appendix fturtle methods method description turtle onrelease(funbtn= add=nonebind fun to mouse-button-release event on this turtle on canvas argumentsfun function with two argumentsto which will be assigned the coordinates of the clicked point on the canvas num number of the mouse-button defaults to (left mouse buttonturtle pencolor(*argsreturn or set the pencolor argumentsfour input formats are allowedpencolor(return the current pencolor as color specification stringpossibly in hex-number format (see examplemay be used as input to another color/pencolor/fillcolor call pencolor(colorstrings is tk color specification stringsuch as "redor "yellowpencolor((rgb)* tupleof rgand bwhich representan rgb colorand each of rgand are in the range colormodewhere colormode is either or pencolor(rgbrgand represent an rgb colorand each of rgand are in the range colormode if turtleshape is polygonthe outline of that polygon is drawn with the newly set pencolor example (for turtle instance named turtle)turtle pencolor('brown'tup ( turtle pencolor(tupturtle pencolor('# cc cturtle pendown(pull the pen down drawing when moving aliasespd down example (for turtle instance named turtle)turtle pendown(turtle pensize(width=noneset or return the line thickness aliaseswidth argumentwidth positive number this copy belongs to 'acha |
14,723 | method description set the line thickness to width or return it if resizemode is set to "autoand turtleshape is polygonthat polygon is drawn with the same line thickness if no argument is givencurrent pensize is returned example (for turtle instance named turtle)turtle pensize( turtle pensize( from here on lines of width are drawn turtle penup(pull the pen up no drawing when moving aliasespu up example (for turtle instance named turtle)turtle penup(turtle radians(set the angle measurement units to radians example (for turtle instance named turtle)turtle heading( turtle radians(turtle heading( turtle reset(delete the turtle' drawings from the screenre-center the turtle and set variables to the default values example (for turtle instance named turtle)turtle position(( ,- turtle heading( turtle reset(turtle position(( , turtle heading( turtle setheading(to_angleset the orientation of the turtle to to_angle aliasesseth argumentto_angle number (integer or floatset the orientation of the turtle to to_angle here are some common directions in degreesthis copy belongs to 'acha |
14,724 | appendix fturtle methods method description standard modelogo-mode east north north east west south south west example (for turtle instance named turtle)turtle setheading( turtle heading( turtle shape(name=noneset turtle shape to shape with given name return current shapename optional argumentname stringwhich is valid shapename set turtle shape to shape with given name orif name is not givenreturn name of current shape shape with name must exist in the turtlescreen' shape dictionary initially there are the following polygon shapes'arrow''turtle''circle''square''triangle''classicto learn about how to deal with shapes see screen-method register_shape example (for turtle instance named turtle)turtle shape('arrowturtle shape("turtle"turtle shape('turtleturtle showturtle(makes the turtle visible aliasesst example (for turtle instance named turtle)turtle hideturtle(turtle showturtle(turtle speed(speed=nonereturn or set the turtle' speed optional argumentspeed an integer in the range or speedstring (see belowset the turtle' speed to an integer value in the range if no argument is givenreturn current speed if input is number greater than or smaller than speed is set to this copy belongs to 'acha |
14,725 | method description turtle undo(undo (repeatedlythe last turtle action number of available undo actions is determined by the size of the undobuffer example (for turtle instance named turtle)for in range( )turtle fd( )turtle lt( for in range( )turtle undo(turtle write(argmove=falsealign='left'font=('arial' 'normal')write text at the current turtle position argumentsarg infowhich is to be written to the turtlescreen move (optionaltrue/false align (optionalone of the strings "left","center"or rightfont (optionala triple (fontnamefontsizefonttypewrite text the string representation of arg at the current turtle position according to align ("left","center"or right"and with the given font if move is truethe pen is moved to the bottom-right corner of the text by defaultmove is false example (for turtle instance named turtle)turtle write('home 'truealign="center"turtle write(( , )trueturtle xcor(return the turtle' coordinate example (for turtle instance named turtle)reset(turtle left( turtle forward( print(turtle xcor() turtle ycor(return the turtle' coordinate example (for turtle instance named turtle)reset(turtle left( turtle forward( print(turtle ycor() this copy belongs to 'acha |
14,726 | this documentation was generated from the python documentation available by typing from turtle import help turtlescreenin the python shell in the documentation found here the variable turtle is reference to turtle object and screen is reference to the turtlescreen object this is subset of that documentation the official python documentation is at org/ method description screen addshape(namesame thing as screen register_shape(namescreen bgcolor(*argsset or return backgroundcolor of the turtlescreen arguments (if given) color string or three numbers in the range colormode or -tuple of such numbers example (for turtlescreen instance named screen)screen bgcolor("orange"screen bgcolor('orangescreen bgcolor( , , screen bgcolor('# (cspringer international publishing switzerland lee and hubbarddata structures and algorithms with pythonundergraduate topics in computer sciencedoi -- this copy belongs to 'acha |
14,727 | appendix gturtlescreen methods method description screen bgpic(picname=noneset background image or return name of current backgroundimage optional argumentpicname stringname of gif-file or "nopicif picname is filenameset the corresponing image as background if picname is "nopic"delete backgroundimageif present if picname is nonereturn the filename of the current backgroundimage example (for turtlescreen instance named screen)screen bgpic('nopicscreen bgpic("landscape gif"screen bgpic('landscape gifscreen clear(delete all drawings and all turtles from the turtlescreen reset empty turtlescreen to its initial statewhite backgroundno backgroundimageno eventbindings and tracing on example (for turtlescreen instance named screen)screen clear(notethis method is not available as function screen colormode(cmode=nonereturn the colormode or set it to or optional argumentcmode one of the values or rgb values of colortriples have to be in range cmode example (for turtlescreen instance named screen)screen colormode( screen colormode( turtle pencolor( , , screen delay(delay=nonereturn or set the drawing delay in milliseconds optional argumentdelay positive integer example (for turtlescreen instance named screen)screen delay( screen delay( this copy belongs to 'acha |
14,728 | method description screen getcanvas(return the canvas of this turtlescreen example (for screen instance named screen)cv screen getcanvas(cv screen getshapes(return list of names of all currently available turtle shapes example (for turtlescreen instance named screen)screen getshapes(['arrow''blank''circle''turtle'screen listen(xdummy=noneydummy=noneset focus on turtlescreen (in order to collect key-eventsdummy arguments are provided in order to be able to pass listen to the onclick method example (for turtlescreen instance named screen)screen listen(screen mode(mode=noneset turtle-mode ('standard''logoor 'world'and perform reset optional argumentmode on of the strings 'standard''logoor 'worldmode 'standardis compatible with turtle py mode 'logois compatible with most logo-turtle-graphics mode 'worlduses userdefined 'worldcoordinates*attention*in this mode angles appear distorted if / unit-ratio doesn' equal if mode is not givenreturn the current mode mode initial turtle heading positive angles 'standardto the right (eastcounterclockwise 'logoupward (northclockwise examplesmode('logo'resets turtle heading to north mode('logothis copy belongs to 'acha |
14,729 | appendix gturtlescreen methods method description screen onclick(funbtn= add=nonebind fun to mouse-click event on canvas argumentsfun function with two argumentsthe coordinates of the clicked point on the canvas num the number of the mouse-buttondefaults to example (for turtlescreen instance named screen and turtle instance named turtle)screen onclick(turtle goto##subsequently clicking into the turtlescreen will ##make the turtle move to the clicked point screen onclick(none##event-binding will be removed screen onkey(funkeybind fun to key-release event of key argumentsfun function with no arguments key stringkey ( " "or key-symbol ( "space"in order to be able to register key-eventsturtlescreen must have focus (see method listen example (for turtlescreen instance named screen and turtle instance named turtle)def ()turtle fd( turtle lt( screen onkey( "up"screen listen(##subsequently the turtle can be moved by ##repeatedly pressing the up-arrow key##consequently drawing hexagon this copy belongs to 'acha |
14,730 | method description screen onkeypress(funkey=nonebind fun to key-press event of key if key is givenor to any key-press-event if no key is given argumentsfun function with no arguments key stringkey ( " "or key-symbol ( "space"in order to be able to register key-eventsturtlescreen must have focus (see method listen example (for turtlescreen instance named screen and turtle instance named turtle)def ()turtle fd( screen onkey( "up"screen listen(##subsequently the turtle can be moved by ##repeatedly pressing the up-arrow key##or by keeping pressed the up-arrow key ##consequently drawing hexagon screen ontimer(funt= install timerwhich calls fun after milliseconds argumentsfun function with no arguments number > example (for turtlescreen instance named screen)running true def ()if runningturtle fd( turtle lt( screen ontimer( (##makes the turtle marching around running false this copy belongs to 'acha |
14,731 | appendix gturtlescreen methods method description screen register_shape(nameshape=noneadds turtle shape to turtlescreen' shapelist arguments( name is the name of gif-file and shape is none installs the corresponding image shape !image-shapes do not rotate when turning the turtle!so they do not display the heading of the turtle( name is an arbitrary string and shape is tuple of pairs of coordinates installs the corresponding polygon shape ( name is an arbitrary string and shape is (compoundshape object installs the corresponding compound shape to use shapeyou have to issue the command shape(shapenamecallregister_shape("turtle gif"-orregister_shape("tri"(( , )( , )(- , ))example (for turtlescreen instance named screen)screen register_shape("triangle"(( ,- ),( , ),(- ,- ))screen reset(reset all turtles on the screen to their initial state example (for turtlescreen instance named screen)screen reset(screen screensize(canvwidth=nonecanvheight=nonebg=noneresize the canvas the turtles are drawing on optional argumentscanvwidth positive integernew width of canvas in pixels canvheight positive integernew height of canvas in pixels bg colorstring or color-tupelnew backgroundcolor if no arguments are givenreturn current (canvaswidthcanvasheightdo not alter the drawing window to observe hidden parts of the canvas use the scrollbars (can make visible those parts of drawingwhich were outside the canvas before!example (for turtle instance named turtle)turtle screensize( , ## to search for an erroneously escaped turtle ;-this copy belongs to 'acha |
14,732 | method description screen setworldcoordinates(llxllyurxuryset up user defined coordinate-system argumentsllx numberx-coordinate of lower left corner of canvas lly numbery-coordinate of lower left corner of canvas urx numberx-coordinate of upper right corner of canvas ury numbery-coordinate of upper right corner of canvas set up user coodinat-system and switch to mode 'worldif necessary this performs screen reset if mode 'worldis already activeall drawings are redrawn according to the new coordinates but attentionin user-defined coordinatesystems angles may appear distorted (see screen mode()example (for turtlescreen instance named screen)screen setworldcoordinates(- ,- , , for in range( )turtle left( turtle forward( screen title(titlestrset the title of the turtle graphics screen the title appears in the title bar of the window screen tracer( =nonedelay=noneturns turtle animation on/off and set delay for update drawings optional argumentsn nonnegative integer delay nonnegative integer if is givenonly each -th regular screen update is really performed (can be used to accelerate the drawing of complex graphics second arguments sets delay value (see rawturtle delay()example (for turtlescreen instance named screen)screen tracer( dist for in range( )turtle fd(distturtle rt( dist + screen turtles(return the list of turtles on the screen example (for turtlescreen instance named screen)screen turtles([this copy belongs to 'acha |
14,733 | appendix gturtlescreen methods method description screen update(perform turtlescreen update screen window_height(return the height of the turtle window example (for turtlescreen instance named screen)screen window_height( screen window_width(return the width of the turtle window example (for turtlescreen instance named screen)screen window_width( screen mainloop(starts event loop calling tkinter' mainloop function must be last statement in turtle graphics program must not be used if script is run from within idle in - mode (no subprocessfor interactive use of turtle graphics example (for turtlescreen instance named screen)screen mainloop(screen numinput(titlepromptdefault=noneminval=nonemaxval=nonepop up dialog window for input of number argumentstitle is the title of the dialog windowprompt is text mostly describing what numerical information to input defaultdefault value minvalminimum value for imput maxvalmaximum value for input the number input must be in the range minval maxval if these are given if nota hint is issued and the dialog remains open for correction return the number input if the dialog is canceledreturn none example (for turtlescreen instance named screen)screen numinput("poker""your stakes:" minval= maxval= screen textinput(titlepromptpop up dialog window for input of string argumentstitle is the title of the dialog windowprompt is text mostly describing what information to input return the string input if the dialog is canceledreturn none example (for turtlescreen instance named screen)screen textinput("nim""name of first player:"this copy belongs to 'acha |
14,734 | the draw program this is the sample drawing application from the first it illustrates the use of the tkinter library including many widgets and mouse handling this program can be downloaded from the text' website the and modules the and modules and import import import import import xml dom minidom the commands by gotocommand def width self self width width color color the draw method each command draws command using the given def draw width width pencolor color goto the method method when command the command how format def '<command = = width = width = goto circlecommand def width radius radius width width (cspringer international publishing switzerland lee and hubbarddata structures and algorithms with pythonundergraduate topics in computer sciencedoi -- this copy belongs to 'acha |
14,735 | appendix hcomplete programs color color def draw width width pencolor color turtle radius def '<command = width = width = beginfillcommand def color color def draw turtle color turtle begin_fill (def endfillcommand def pass def draw turtle end_fill (def penupcommand def pass def draw penup def penup pendowncommand def pass def draw pendown def pendown the container ob class pylist def self gclist [ meant the append method add commands def append it it method by undo remove def gclist gclist [- the sequence method when each to the the loop that this copy belongs to 'acha |
14,736 | def for in yield when on def return len the from frame means frame code which frame frame def =none super pack buildwindow graphicscommands method them gui and def buildwindow the window the draw below how menu the = means menus can be from window which menu menu bar code by new menu below when the same and below the menu below on window def newwindow up be new be drawn back empty graphicscommands be graphicscommands graphicscommands would make newwindow method were would be anymore once newwindow method et penup goto pendown update screen graphicscommands add_command new ,command=newwindow the adds an xml def xmldoc xml dom minidom graphicscommandselement xmldoc getelementsbytagname graphicscommands graphicscommands graphicscommandselement getelementsbytagname command commandelement graphicscommands type commandelement command commandelement commandelement command =goto float value float value width width this copy belongs to 'acha |
14,737 | appendix hcomplete programs color color value cmd gotocommand width command = radius float radius value width width color color value cmd circlecommand width command = color color value cmd beginfillcommand command = cmd endfillcommand command =penup cmd penupcommand command =pendown cmd pendowncommand else unknown command command graphicscommands append cmd def filename askopenfilename = graphics newwindow new graphicscommands commands from parse filename cmd graphicscommands cmd draw window drawn update add_command load ,commandl def dt filename askopenfilename = graphics penup goto pendown # # cmd penupcommand graphicscommands append cmd cmd gotocommand # graphicscommands append cmd cmd pendowncommand graphicscommands append cmd update parse filename cmd graphicscommands cmd draw this copy belongs to 'acha |
14,738 | update add_command load ,commanda dt the an xml def open "wf ' cmd graphicscommands ' cmdn write close def save as write filename add_command save as ,commands add_command ,commands add_cascade ,menuf window menu menub the on window canvas width = pack left by wt we can have draw on and same wt makes shape shape screen et getscreen causes the to not update the ondrag below program bombs around screen on window where and the pad some empty around the on the on side frame padx pady pack right both widget packing puts at the top of the width pack widget allows the user to width below you can and of the widget to val the widthsize to needed must be widthsize stringvar widthentry entry sidebar =widthsize pack this copy belongs to 'acha |
14,739 | appendix hcomplete programs widthsize set radiuslabel label sidebar ext =radius pack gva radiusentry entry sidebar radiussize set pack an when the below when draw def when drawing command and command drawn by draw method dding command graphicscommands means remember cmd circlecommand cmd draw graphicscommands append cmd two needed and back when undo must have update screen the both expand draw commandc pack both the mode below be rgb form red the mode red be by two number from -ff the same and the below and #rrggbb colormode pen pack pencolor gv penentry sidebar =pencolor pack the black # def color colorchooser askcolor none pencolor set )- - ] pen commandg pack both label sidebar text= color pack stringvar entry sidebar pack # def color colorchooser askcolor none set color )- - ]fillcolorbutton commandg pack both this copy belongs to 'acha |
14,740 | def cmd beginfillcommand cmd draw graphicscommands append cmd commandb pack both def cmd endfillcommand cmd draw graphicscommands append cmd end commande pack both pen down pack def penuphandler cmd penupcommand cmd draw pen up graphicscommands append cmd penupbutton pen up command=penuphandler penupbutton pack both def pendownhandler cmd pendowncommand cmd draw pen down graphicscommands append cmd pendownbutton pen down command=pendownhandler pendownbutton pack both one mouse on def when mouse and pen the needed the width but the widget as cmd gotocommand cmd draw graphicscommands append cmd update screen how we mouse screen onclick clickhandler def cmd gotocommand cmd draw graphicscommands append cmd update screen ondrag undoes command by from and def undohandler graphicscommands graphicscommands et penup goto pendown this copy belongs to 'acha |
14,741 | appendix hcomplete programs cmd graphicscommands cmd draw update screen undohandler screen the main gui program window then which and has on makes the when def main tk drawingapp drawingapp mainloop program completed __name__ =__main__ main the scope program this is the sample program from the first that illustrates the use of scope within program this program can be downloaded from the text' website import math math def global * return thearea def main global historyofprompts historyofoutput def prompt input prompt append prompt return def showoutput append print val getinput enter the of this copy belongs to 'acha |
14,742 | float rstring val area print showoutput the __name__ =__main__ main import import import import import the sort animation tkinter turtle random time math wt def canvas super dot shape dot speed penup goto def return " xcor " ycor def return ycor other ycor the from frame frame def =none super pack buildwindow paused stop running def buildwindow def seq pivotindex seq et red penup goto pendown goto stop update why once doesn seem some this copy belongs to 'acha |
14,743 | appendix hcomplete programs et red penup goto pendown goto stop update + stop - while < while < and not seq += while < and seq -= if tmp seq seq seq seq goto seq seq tmp seq goto seq update += -= seq seq seq goto seq seq seq goto seq seq green update et white penup goto pendown goto seq update return def seq > return stopping return seq stopping return seq stopping return seq def seq seq seq def merge seq mid length stop this copy belongs to 'acha |
14,744 | math et blue penup goto ,- pendown et forward length update lst [ start mid merge two each has more while mid and seq seq append seq seq goto seq += else append seq seq goto seq += update copy mid while mid append seq seq goto seq += update copy mid while mid append seq seq goto seq += update copy back range seq goto green update def seq we must > when we empty = - >stop - return mid stopping return stop- math et red penup goto ,- pendown et forward length update this copy belongs to 'acha |
14,745 | appendix hcomplete programs why once doesn seem some et red penup goto ,- pendown et forward length update seq mid stopping return seq mid stopping return et blue penup goto ,- pendown et forward length update merge seq mid update et white goto - ,- pendown et forward length + update def mergesort seq seq seq def seq minindex seq minindex green range seq seq minindex seq seq minindex minindex seq minindex green minindex def seq range seq minindex seq stopping return tmp seq seq seq minindex seq minindex tmp seq goto seq seq minindex goto minindex seq minindex seq green def pause while paused time update screen this copy belongs to 'acha |
14,746 | def paused pause stop pause running update screen return true return master animations menu menu bar def screen update screen def newwindow clear ( running stop true add_command ,command=newwindow add_command ,commands add_cascade ,menuf menub canvas width = pack left wt et ht speed screen et getscreen screen frame padx pady pack right both speed pack speed =speed pack speed def running true clear ( , , , screen master animation seq range stopping return point screen green seq append this copy belongs to 'acha |
14,747 | appendix hcomplete programs update screen range stopping return random , seq seq seq seq seq goto seq seq goto seq seq seq seq running stop commands pack both def running true clear ( , , width screen merge seq range stopping return point screen green seq append update screen range stopping return random , seq seq seq seq seq goto seq seq goto seq seq seq screen mergesort seq running stop merge commandm pack both def running true this copy belongs to 'acha |
14,748 | clear ( , , , width screen master animation seq range stopping return point screen green seq append update screen range stopping return random , seq seq seq seq seq goto seq seq goto seq seq seq screen seq running stop commandq pack both def paused not paused pause commandp pack both def not paused and stop true stop commands pack both screen the main gui program window then which and has on makes the when def main tk anim anim mainloop __name__ =__main__ main this copy belongs to 'acha |
14,749 | appendix hcomplete programs the plotdata program this is the plot program that is used throughout the text to plot experimentally gathered data so it can be visualized this program can be downloaded from the text' website import import import import import import import turtle tkinter colorchooser tkinter filedialog xml dom minidom math sys frame def =none =none super self datafile datafile pack buildwindow def buildwindow master menu menu bar def =none =none filename askopenfilename = et penup goto pendown update et color black xmldoc xml dom minidom xmldoc getelementsbytagname plotelement master value getelementsbytagname axes getelementsbytagname xaxiselement data getelementsbytagname yaxiselement data xattr xaxiselement yattr yaxiselement minx maxx miny maxy min max min max maxx minx maxy miny minx miny this copy belongs to 'acha |
14,750 | max( -round math max( -round math maxy minx - miny maxx maxy et ht penup goto minx miny pendown goto maxx miny penup goto minx miny pendown goto minx maxy penup goto miny , bold goto minx maxy , bold range minx miny penup goto minyy pendown goto miny- penup goto miny- % )% , normal penup goto minxx pendown goto minx- goto minx- % )% , normal sequences getelementsbytagname sequence sequence sequences sequence value color color value et color color penup goto , bold sequence getelementsbytagname datapoints [ attr attributes float value float value goto dot pendown this copy belongs to 'acha |
14,751 | appendix hcomplete programs for datapoint in datapoints datapoint float value float value goto dot update add_command load data ,commandl add_command ,commands add_cascade ,menuf menub canvas width = = pack left wt screen et getscreen screen none loadfile self datafile strip def main tk none len argv sys argv plotapp plotapp mainloop program completed __name__ =__main__ main the tic tac toe application this is the starter code for an exercise in constructing tic tac toe game this program can be downloaded from the text' website from import import messagebox import import random import math import import time import screenmin screenmax human - computer board when board you may want make copy board this copy belongs to 'acha |
14,752 | can be copy board immutable from board def board=none =none screen screen =none board none board items range rowlst range board==none append (dummy else append board append method def return screen the method row board row board row column def return items index board row and column board can be method method two and same reader you must complete function def __eq__ pass method mutate board dummy way board can be when new game not be when new game def screen range range goto - ,- dummy screen method an board has won human has won - reader you must complete function def pass method board up no dummy otherwise should reader you must complete function def pass method draw and of board on def drawxos this copy belongs to 'acha |
14,753 | appendix hcomplete programs row range range row row row goto * + ,row * + update when no move has been made board when no move has been made dummy def pass def return def goto pass and below by the above then on wt wt def super ht , , , , , , , , , , , , , , , , , , , shape penup speed goto - ,- def computer wt def super ht shape penup speed goto - ,- def human the minimax computer - human and board when computer minimax maximum moves computer make when human minimax minimum moves human make minimax by each move computer move and human move by making move whose and minimax the when board someone has won board reader you must complete function def minimax board pass this copy belongs to 'acha |
14,754 | ct ct frame def =none super pack buildwindow paused stop running human locked false def buildwindow cv , , , , cv pack left wt cv screen getscreen screen ( screenmin screenmin screenmax screenmax screen bgcolor white ht frame frame frame pack right both board board none def screen screen ( screenmin screenmin screenmax screenmax screen bgcolor white screen wt cv ht pu width green range penup goto , pendown goto , penup goto * + pendown goto * + update def newgame drawgrid human board locked =false update def newgame drawgrid frame new game commands pack this copy belongs to 'acha |
14,755 | appendix hcomplete programs def master frame commandq pack def computerturn the from making up mind locked true minimax move make reader you must complete code code maxmove move move row and column maxmove would be row maxmove board row cv locked false def not row col int board row cv computer board drawxos not board and not abs board computerturn human board drawxos else locked true board = messagebox showwarning game over wins board =- messagebox showwarning game over " wins how happen board messagebox showwarning game over was screen mouseclick screen def main tk toe ct ct mainloop __name__ =__main__ main this copy belongs to 'acha |
14,756 | the connect four front-end this provides the gui front-end to the connect four game presented in the last of the text this can serve as front-end for computer opponent back-end this program can be downloaded from the text' website import import import import import turtle subprocess tkinter sys time the program program and program communicate and when command program when program program means program python other new game by code code ok human move by move which - move be on code ok computer move code ok and move which - game not over computer won =human won must be program work sample code however program may be any programming language defun play gameboard make-hash- memo make-hash- lastmove do gameboard msgid cond msgid human human humanturn gameboard msgid new game message progn gameboard make-hash- memo make-hash- format to the computer ready msgid computer message rt gameboard msgid game cond gameboard the computer won gameboard - the human won gameboard this copy belongs to 'acha |
14,757 | appendix hcomplete programs ; draw format the game format computer human - wt def canvas row app super val row row col col app penup ht goto * + ,row * + def horc horc =computer shape else shape drop def getowner return def row def drop goto , screen speed self st goto * + row * + goto * + row * + goto * + row * + screen frame def =none super pack buildwindow running def buildwindow connect four menu menu bar add_command ,commands add_cascade ,menuf menub this copy belongs to 'acha |
14,758 | canvas width = pack left wt et ht screen et getscreen , , , screen register_shape blackchecker screen register_shape redchecker screen screen bgcolor yellow width range penup goto , pendown goto , et ht update def toother write \ toother fromother = messagebox game over won = messagebox game over you won = messagebox game over print status is status return def computerturn toother write \ toother fromother computer = move fromother move move row move move row computer update def humanturn running return status checkstatus ! return running true row while row > and row this copy belongs to 'acha |
14,759 | appendix hcomplete programs row row row then we column was running true return row do human toother write \ toother toother write \ toother fromother print status is status row human update check game status checkstatus = do computer computerturn checkstatus running matrix range row range canvas row append append row update humanturn frame padx pady raised pt pack right both def newgame toother write \ toother fromother row token row token update kb ,command=computerturn kb pack ng new game ,command=newgame ng pack popen = this copy belongs to 'acha |
14,760 | contents advantages and limitations of decision trees bootstrap aggregation random forests boosting exercises deep learning introduction feed-forward neural networks back-propagation methods for training steepest descent levenberg-marquardt method limited-memory bfgs method adaptive gradient methods examples in python simple polynomial regression image classification exercises linear algebra and functional analysis vector spacesbasesand matrices inner product complex vectors and matrices orthogonal projections eigenvalues and eigenvectors leftand right-eigenvectors matrix decompositions ( )lu decomposition woodbury identity cholesky decomposition qr decomposition and the gram-schmidt procedure singular value decomposition solving structured matrix equations functional analysis fourier transforms discrete fourier transform fast fourier transform multivariate differentiation and optimization multivariate differentiation taylor expansion chain rule optimization theory convexity and optimization lagrangian method duality |
14,761 | xi numerical root-finding and minimization newton-like methods quasi-newton methods normal approximation method nonlinear least squares constrained minimization via penalty functions probability and statistics random experiments and probability spaces random variables and probability distributions expectation joint distributions conditioning and independence conditional probability independence expectation and covariance conditional density and conditional expectation functions of random variables multivariate normal distribution convergence of random variables law of large numbers and central limit theorem markov chains statistics estimation method of moments maximum likelihood method confidence intervals hypothesis testing python primer getting started python objects types and operators functions and methods modules flow control iteration classes files numpy creating and shaping arrays slicing array operations random numbers matplotlib creating basic plot |
14,762 | xii pandas series and dataframe manipulating data frames extracting information plotting scikit-learn partitioning the data standardization fitting and prediction testing the model system callsurl accessand speed-up bibliography index |
14,763 | in our present world of automationcloud computingalgorithmsartificial intelligenceand big datafew topics are as relevant as data science and machine learning their recent popularity lies not only in their applicability to real-life questionsbut also in their natural blending of many different disciplinesincluding mathematicsstatisticscomputer scienceengineeringscienceand finance to someone starting to learn these topicsthe multitude of computational techniques and mathematical ideas may seem overwhelming some may be satisfied with only learning how to use off-the-shelf recipes to apply to practical situations but what if the assumptions of the black-box recipe are violatedcan we still trust the resultshow should the algorithm be adaptedto be able to truly understand data science and machine learning it is important to appreciate the underlying mathematics and statisticsas well as the resulting algorithms the purpose of this book is to provide an accessibleyet comprehensiveaccount of data science and machine learning it is intended for anyone interested in gaining better understanding of the mathematics and statistics that underpin the rich variety of ideas and machine learning algorithms in data science our viewpoint is that computer languages come and gobut the underlying key ideas and algorithms will remain forever and will form the basis for future developments before we turn to description of the topics in this bookwe would like to say few words about its philosophy this book resulted from various courses in data science and machine learning at the universities of queensland and new south walesaustralia when we taught these courseswe noticed that students were eager to learn not only how to apply algorithms but also to understand how these algorithms actually work howevermany existing textbooks assumed either too much background knowledge ( measure theory and functional analysisor too little (everything is black box)and the information overload from often disjointed and contradictory internet sources made it more difficult for students to gradually build up their knowledge and understanding we therefore wanted to write book about data science and machine learning that can be read as linear storywith substantial "backstoryin the appendices the main narrative starts very simply and builds up gradually to quite an advanced level the backstory contains all the necessary xiii |
14,764 | keywords xvii preface backgroundas well as additional informationfrom linear algebra and functional analysis (appendix )multivariate differentiation and optimization (appendix )and probability and statistics (appendix cmoreoverto make the abstract ideas come alivewe believe it is important that the reader sees actual implementations of the algorithmsdirectly translated from the theory after some deliberation we have chosen python as our programming language it is freely available and has been adopted as the programming language of choice for many practitioners in data science and machine learning it has many useful packages for data manipulation (often ported from rand has been designed to be easy to program gentle introduction to python is given in appendix to keep the book manageable in size we had to be selective in our choice of topics important ideas and connections between various concepts are highlighted via keywords and page references (indicated by +in the margin key definitions and theorems are highlighted in boxes whenever feasible we provide proofs of theorems finallywe place great importance on notation it is often the case that once consistent and concise system of notation is in placeseemingly difficult ideas suddenly become obvious we use different fonts to distinguish between different types of objects vectors are denoted by letters in boldface italicsxxand matrices by uppercase letters in boldface roman fontak we also distinguish between random vectors and their values by using upper and lower case letterse (random vectorand (its value or outcomesets are usually denoted by calligraphic letters gh the symbols for probability and expectation are and erespectively distributions are indicated by sans serif fontas in bin and gammaexceptions are the ubiquitous notations and for the normal and uniform distributions summary of the most important symbols and abbreviations is given on pages xvii-xxi data science provides the language and techniques necessary for understanding and dealing with data it involves the designcollectionanalysisand interpretation of numerical datawith the aim of extracting patterns and other useful information machine learningwhich is closely related to data sciencedeals with the design of algorithms and computer resources to learn from data the organization of the book follows roughly the typical steps in data science projectgathering data to gain information about research questioncleaningsummarizationand visualization of the datamodeling and analysis of the datatranslating decisions about the model into decisions and predictions about the research question as this is mathematics and statistics oriented bookmost emphasis will be on modeling and analysis we start in with the readingstructuringsummarizationand visualization of data using the data manipulation package pandas in python although the material covered in this requires no mathematical knowledgeit forms an obvious starting point for data scienceto better understand the nature of the available data in we introduce the main ingredients of statistical learning we distinguish between supervised and unsupervised learning techniquesand discuss how we can assess the predictive performance of (un)supervised learning methods an important part of statistical learning is the modeling of data we introduce various useful models in data science including linearmultivariate gaussianand bayesian models many algorithms in machine learning and data science make use of monte carlo techniqueswhich is the topic of monte carlo can be used for simulationestimationand optimization is concerned with unsupervised learningwhere we discuss techniques such as density estimationclusteringand principal component analysis we then turn our attention to supervised learning |
14,765 | xv in and explain the ideas behind broad class of regression models thereinwe also describe how python' statsmodels package can be used to define and analyze linear models builds upon the previous regression by developing the powerful concepts of kernel methods and regularizationwhich allow the fundamental ideas of to be expanded in an elegant wayusing the theory of reproducing kernel hilbert spaces in we proceed with the classification taskwhich also belongs to the supervised learning frameworkand consider various methods for classificationincluding bayes classificationlinear and quadratic discriminant analysisk-nearest neighborsand support vector machines in we consider versatile methods for regression and classification that make use of tree structures finallyin we consider the workings of neural networks and deep learningand show that these learning algorithms have simple mathematical interpretation an extensive range of exercises is provided at the end of each python code and data sets for each can be downloaded from the github siteacknowledgments some of the python code for and was adapted from [ we thank benoit liquet for making this availableand lauren jones for translating the code into python we thank all who through their commentsfeedbackand suggestions have contributed to this bookincluding qibin duanluke taylorremi mouzayekharry goodmanbryce stansfieldryan tongsdillon steylbill ruddnan yechristian hirschchris van der heidesarat mokaaapeli vuorinenjoshua rossgiang nguyenand the anonymous referees david grubbs deserves special accollade for his professionalism and attention to detail in his role as editor for this book the book was test-run during the summer school of the australian mathematical sciences institute more than bright upper-undergraduate (honoursstudents used the book for the course mathematical methods for machine learningtaught by zdravko botev we are grateful for the valuable feedback that they provided our special thanks go out to robert salomoneliam berryrobin carrickand sam daleywho commented in great detail on earlier versions of the entire book and wrote and improved our python code their enthusiasmperceptivenessand kind assistance have been invaluable of coursenone of this work would have been possible without the loving supportpatienceand encouragement from our familiesand we thank them with all our hearts this book was financially supported by the australian research council centre of excellence for mathematical statistical frontiersunder grant number ce dirk kroesezdravko botevthomas taimreand radislav vaisman brisbane and sydney |
14,766 | we couldof courseuse any notation we wantdo not laugh at notationsinvent themthey are powerful in factmathematics isto large extentinvention of better notations richard feynman we have tried to use notation system that isin order of importancesimpledescriptiveconsistentand compatible with historical choices achieving all of these goals all of the time would be impossiblebut we hope that our notation helps to quickly recognize the type or "flavorof certain mathematical objects (vectorsmatricesrandom vectorsprobability measuresetc and clarify intricate ideas we make use of various typographical aidsand it will be beneficial for the reader to be aware of some of these boldface font is used to indicate composite objectssuch as column vectors [ xn ]and matrices [xi note also the difference between the upright bold font for matrices and the slanted bold font for vectors random variables are generally specified with upper case roman letters xyz and their outcomes with lower case letters xyz random vectors are thus denoted in upper case slanted bold fontx [ xn ]sets of vectors are generally written in calligraphic fontsuch as xbut the set of real numbers uses the common blackboard bold font expectation and probability also use the latter font probability distributions use sans serif fontsuch as bin and gamma exceptions to this rule are the "standardnotations and for the normal and uniform distributions we often omit brackets when it is clear what the argument is of function or operator for examplewe prefer ex to [ xvii |
14,767 | xviii we employ color to emphasize that certain words refer to datasetfunctionor package in python all code is written in typewriter font to be compatible with past notation choiceswe introduced special blue symbol for the model (designmatrix of linear model important notation such as ggis often defined in mnemonic waysuch as for "training" for "guess"gfor the "star(that isoptimalguessand for "losswe will occasionally use bayesian notation convention in which the same symbol is used to denote different (conditionalprobability densities in particularinstead of writing fx (xand fx ( yfor the probability density function (pdfof and the conditional pdf of given ywe simply write (xand ( ythis particular style of notation can be of great descriptive valuedespite its apparent ambiguity general font/notation rules scalar vector random vector matrix set estimate or approximation optimal average common mathematical symbols for all is proportional to is distributed as there exists is perpendicular to iid are independent and identically distributed as approx is approximately distributed as gradient of hessian of is approximately is much smaller than ~~iid cp has continuous derivatives of order is asymptotically direct sum |
14,768 | xix elementwise product intersection :==is defined as -converges almost surely to union - converges in distribution to -converges in probability to -converges in -norm to dxe smallest integer larger than xmax{ lp * bxc euclidean norm largest integer smaller than matrix/vector notation axtranspose of matrix or vector - inverse of matrix pseudo-inverse of matrix -inverse of matrix aor transpose of - matrix is positive definite matrix is positive semidefinite dim(xdimension of vector det(adeterminant of matrix |aabsolute value of the determinant of matrix tr(atrace of matrix reserved letters and words set of complex numbers differential symbol expectation the number probability density (discrete or continuousg prediction function {aor indicator function of set the square root of - riskexpected loss |
14,769 | xx loss loss function ln (naturallogarithm set of natural numbers { big- order symbolf (xo( ( )if ( ) ag(xfor some constant as - little- order symbolf (xo( ( )if ( )/ ( as probability measure the number set of real numbers (one-dimensional euclidean spacern -dimensional euclidean space rpositive real line[ deterministic training set random training set model (designmatrix set of integers - probability distributions ber bernoulli beta beta bin binomial exp exponential geom geometric gamma gamma fisher-snedecor normal or gaussian pareto pareto poi poisson student' uniform abbreviations and acronyms cdf cumulative distribution function cmc crude monte carlo ce cross-entropy em expectation-maximization gp gaussian process kde kernel density estimate/estimator |
14,770 | xxi kl kullback-leibler kkt karush-kuhn-tucker iid independent and identically distributed map maximum posteriori mcmc markov chain monte carlo mle maximum likelihood estimator/estimate oob out-of-bag pca principal component analysis pdf probability density function (discrete or continuoussvd singular value decomposition |
14,771 | mporting ummarizing and isualizing data this describes where to find useful data setshow to load them into pythonand how to (re)structure the data we also discuss various ways in which the data can be summarized via tables and figures which type of plots and numerical summaries are appropriate depends on the type of the variable(sin play readers unfamiliar with python are advised to read appendix first introduction data comes in many shapes and formsbut can generally be thought of as being the result of some random experiment -an experiment whose outcome cannot be determined in advancebut whose workings are still subject to analysis data from random experiment are often stored in table or spreadsheet statistical convention is to denote variables -often called features -as columns and the individual items (or unitsas rows it is useful to think of three types of columns in such spreadsheet the first column is usually an identifier or index columnwhere each unit/row is given unique name or id certain columns (featurescan correspond to the design of the experimentspecifyingfor exampleto which experimental group the unit belongs often the entries in these columns are deterministicthat isthey stay the same if the experiment were to be repeated other columns represent the observed measurements of the experiment usuallythese measurements exhibit variabilitythat isthey would change if the experiment were to be repeated there are many data sets available from the internet and in software packages wellknown repository of data sets is the machine learning repository maintained by the university of california at irvine (uci)found at features |
14,772 | these data sets are typically stored in csv (comma separated valuesformatwhich can be easily read into python for exampleto access the abalone data set from this website with pythondownload the file to your working directoryimport the pandas package via import pandas as pd and read in the data as followsabalone pd read_csv ('abalone data ',header noneit is important to add header noneas this lets python know that the first line of the csv does not contain the names of the featuresas it assumes so by default the data set was originally used to predict the age of abalone from physical measurementssuch as shell weight and diameter another useful repository of over data sets from various packages in the programming languagecollected by vincent arel-bundockcan be found atfor exampleto read fisher' famous iris data set from ' datasets package into pythontypeurlprefix 'https :/vincentarelbundock github iordatasets /csv/dataname 'datasets /iris csv iris pd read_csv urlprefix dataname the iris data set contains four physical measurements (sepal/petal length/widthon specimens (eachof species of irissetosaversicolorand virginica note that in this case the headers are included the output of read_csv is dataframe objectwhich is pandas' implementation of spreadsheetsee section the dataframe method head gives the first few rows of the dataframeincluding the feature names the number of rows can be passed as an argument and is by default for the iris dataframewe haveiris head ( unnamed sepal length petal width species setosa setosa setosa setosa setosa [ rows columns the names of the features can be obtained via the columns attribute of the dataframe objectas in iris columns note that the first column is duplicate index columnwhose name (assigned by pandasis 'unnamed we can drop this column and reassign the iris object as followsiris iris drop('unnamed , |
14,773 | the data for each feature (corresponding to its specific namecan be accessed by using python' slicing notation [for examplethe object iris['sepal length'contains the sepal lengths the first three rows of the abalone data set from the uci repository can be found as followsabalone head ( herethe missing headers have been assigned according to the order of the natural numbers the names should correspond to sexlengthdiameterheightwhole weightshucked weightviscera weightshell weightand ringsas described in the file with the name abalone names on the uci website we can manually add the names of the features to the dataframe by reassigning the columns attributeas inabalone columns ['sex ''length ''diameter ''height ''whole weight ','shucked weight ''viscera weight ''shell weight ''rings ' structuring features according to type we can generally classify features as either quantitative or qualitative quantitative features possess "numerical quantity"such as heightagenumber of birthsetc and can either be continuous or discrete continuous quantitative features take values in continuous range of possible valuessuch as heightvoltageor crop yieldsuch features capture the idea that measurements can always be made more precisely discrete quantitative features have countable number of possibilitiessuch as count in contrastqualitative features do not have numerical meaningbut their possible values can be divided into fixed number of categoriessuch as { ,ffor gender or {blueblackbrowngreenfor eye color for this reason such features are also called categorical simple rule of thumb isif it does not make sense to average the datait is categorical for exampleit does not make sense to average eye colors of course it is still possible to represent categorical data with numberssuch as blue black brownbut such numbers carry no quantitative meaning categorical features are often called factors when manipulatingsummarizingand displaying datait is important to correctly specify the type of the variables (featureswe illustrate this using the nutrition_elderly data set from [ ]which contains the results of study involving nutritional measurements of thirteen features (columnsfor elderly individuals (rowsthe data set can be obtained fromexcel files can be read directly into pandas via the read_excel methodquantitative qualitative categorical factors |
14,774 | xls 'http :/www biostatisticien euspringer nutrition_elderly xls nutri pd read_excel (xlsthis creates dataframe object nutri the first three rows are as followspd set_option ('display max_columns ' to fit display nutri head ( gender situation tea cooked_fruit_veg chocol fat [ rows columns you can check the type (or structureof the variables via the info method of nutri nutri info (rangeindex entries to data columns total columns )gender non -null int situation non -null int tea non -null int coffee non -null int height non -null int weight non -null int age non -null int meat non -null int fish non -null int raw_fruit non -null int cooked_fruit_veg non -null int chocol non -null int fat non -null int dtypes int ( memory usage kb all features in nutri are (at the momentinterpreted by python as quantitative variablesindeed as integerssimply because they have been entered as whole numbers the meaning of these numbers becomes clear when we consider the description of the featuresgiven in table table shows how the variable types should be classified table the feature types for the data frame nutri qualitative discrete quantitative continuous quantitative gendersituationfat meatfishraw_fruitcooked_fruit_vegchocol teacoffee heightweightage note that the categories of the qualitative features in the second row of table meatchocol have natural order such qualitative features are sometimes called ordinalin |
14,775 | table description of the variables in the nutritional study [ feature gender situation tea coffee height weight age meat fish raw_fruit cooked_fruit_veg chocol fat unit or coding =male =female =single =living with spouse family status =living with family =living with someone else daily consumption of tea number of cups daily consumption of coffee number of cups height cm weight (actuallymasskg age at date of interview years =never =less than once week =once week consumption of meat = - times week = - times week =every day consumption of fish as in meat consumption of raw fruits as in meat consumption of cooked as in meat fruits and vegetables consumption of chocolate as in meat =butter =margarine =peanut oil type of fat used =sunflower oil for cooking =olive oil =mix of vegetable oils ( isio =colza oil =duck or goose fat description gender contrast to qualitative features without orderwhich are called nominal we will not make such distinction in this book we can modify the python value and type for each categorical featureusing the replace and astype methods for categorical featuressuch as genderwe can replace the value with 'maleand with 'female'and change the type to 'categoryas follows dict { 'male ' :'female 'dictionary specifies replacement nutri ['gender 'nutri ['gender 'replace (dictastype ('category 'the structure of the other categorical-type features can be changed in similar way continuous features such as height should have type floatnutri ['height 'nutri ['height 'astype float |
14,776 | we can repeat this for the other variables (see exercise and save this modified data frame as csv fileby using the pandas method to_csv nutri to_csv ('nutri csv ',index false summary tables it is often useful to summarize large spreadsheet of data in more condensed form table of counts or table of frequencies makes it easier to gain insight into the underlying distribution of variableespecially if the data are qualitative such tables can be obtained with the methods describe and value_counts as first examplewe load the nutri dataframewhich we restructured and saved (see previous sectionas 'nutri csv'and then construct summary for the feature (column'fatnutri pd read_csv ('nutri csv 'nutri ['fat 'describe (count unique top sunflower freq namefat dtype object we see that there are different types of fat used and that sunflower has the highest countwith out of individuals using this type of cooking fat the method value_counts gives the counts for the different fat types nutri ['fat 'value_counts (sunflower peanut olive margarine isio butter duck colza namefat dtype int column labels are also attributes of dataframeand nutri fatfor exampleis exactly the same object as nutri['fat' |
14,777 | it is also possible to use crosstab to cross tabulate between two or more variablesgiving contingency table cross tabulate pd crosstab nutri gender nutri situation situation gender female male couple family single we seefor examplethat the proportion of single men is substantially smaller than the proportion of single women in the data set of elderly people to add row and column totals to tableuse margins=true pd crosstab nutri gender nutri situation margins =truesituation gender female male all couple family single all summary statistics in the followingx [ xn ]is column vector of numbers for our nutri datathe vector couldfor examplecorrespond to the heights of the individuals the sample mean of xdenoted by xis simply the average of the data valuessample mean xi xn = using the mean method in python for the nutri datawe havefor instancenutri ['height 'mean ( the -sample quantile ( of is value such that at least fraction of the data is less than or equal to and at least fraction of the data is greater than or equal to the sample median is the sample -quantile the -sample quantile is also called the percentile the and sample percentiles are called the firstsecondand third quartiles of the data for the nutri data they are obtained as follows nutri ['height 'quantile ( =[ , , ] sample quantile sample median quartiles |
14,778 | sample range sample variance the sample mean and median give information about the location of the datawhile the distance between sample quantiles (say the and quantilesgives some indication of the dispersion (spreadof the data other measures for dispersion are the sample rangemaxi xi mini xi the sample variance (xi ) = sample standard deviation and the sample standard deviation ( for the nutri datathe range (in cmisnutri ['height 'max (nutri ['height 'min ( the variance (in cm isround nutri ['height 'var ( round to two decimal places and the standard deviation can be found viaround nutri ['height 'std ( we already encountered the describe method in the previous section for summarizing qualitative featuresvia the most frequent count and the number of unique elements when applied to quantitative featureit returns instead the minimummaximummeanand the three quartiles for examplethe 'heightfeature in the nutri data has the following summary statistics nutri ['height 'describe (count mean std min \ \ \ max nameheight dtype float visualizing data in this section we describe various methods for visualizing data the main point we would like to make is that the way in which variables are visualized should always be adapted to the variable typesfor examplequalitative data should be plotted differently from quantitative data |
14,779 | for the rest of this sectionit is assumed that matplotlib pyplotpandasand numpyhave been imported in the python code as follows import matplotlib pyplot as plt import pandas as pd import numpy as np plotting qualitative variables suppose we wish to display graphically how many elderly people are living by themselvesas couplewith familyor other recall that the data are given in the situation column of our nutri data assuming that we already restructured the dataas in section we can make barplot of the number of people in each category via the plt bar function of the standard matplotlib plotting library the inputs are the -axis positionsheightsand widths of each bar respectively width the width of the bars [ the bar positions on -axis situation_counts nutri ['situation 'value_counts (plt bar(xsituation_counts width edgecolor 'black 'plt xticks (xsituation_counts index plt show ( couple single family figure barplot for the qualitative variable 'situationplotting quantitative variables we now present few useful methods for visualizing quantitative dataagain using the nutri data set we will first focus on continuous features ( 'age'and then add some specific graphs related to discrete features ( 'tea'the aim is to describe the variability present in single feature this typically involves central tendencywhere observations tend to gather aroundwith fewer observations further away the main aspects of the distribution are the location (or centerof the variabilitythe spread of the variability (how far the values extend from the center)and the shape of the variabilitye whether or not values are spread symmetrically on either side of the center barplot |
14,780 | boxplot boxplot boxplot can be viewed as graphical representation of the five-number summary of the data consisting of the minimummaximumand the firstsecondand third quartiles figure gives boxplot for the 'agefeature of the nutri data plt boxplot nutri ['age ']widths =width ,vertfalse plt xlabel ('age 'plt show (the widths parameter determines the width of the boxplotwhich is by default plotted vertically setting vert=false plots the boxplot horizontallyas in figure age figure boxplot for 'agethe box is drawn from the first quartile ( to the third quartile ( the vertical line inside the box signifies the location of the median so-called "whiskersextend to either side of the box the size of the box is called the interquartile rangeiqr the left whisker extends to the largest of (athe minimum of the data and (bq iqr similarlythe right whisker extends to the smallest of (athe maximum of the data and (bq iqr any data point outside the whiskers is indicated by small hollow dotindicating suspicious or deviant point (outliernote that boxplot may also be used for discrete quantitative features histogram histogram histogram is common graphical representation of the distribution of quantitative feature we start by breaking the range of the values into number of bins or classes we tally the counts of the values falling in each bin and then make the plot by drawing rectangles whose bases are the bin intervals and whose heights are the counts in python we can use the function plt hist for examplefigure shows histogram of the ages in nutriconstructed via the following python code weights np ones_like nutri age)nutri age count (plt histnutri age ,bins = weights =weights facecolor ='cyan 'edgecolor ='black 'linewidth = plt xlabel ('age 'plt ylabel ('proportion of total 'plt show ( |
14,781 | here bins were used rather than using raw counts (the default)the vertical axis this is achieved by choosing the here gives the percentage in each classdefined by count total "weightsparameter to be equal to the vector with entries / with length various plotting parameters have also been changed proportion of total age figure histogram of 'agehistograms can also be used for discrete featuresalthough it may be necessary to explicitly specify the bins and placement of the ticks on the axes empirical cumulative distribution function the empirical cumulative distribution functiondenoted by fn is step function which jumps an amount / at observation valueswhere is the number of tied observations at that value for observations xn fn (xis the fraction of observations less than or equal to xi number of xi {xi ( fn (xn = where denotes the indicator functionthat is {xi xis equal to when xi and otherwise to produce plot of the empirical cumulative distribution function we can use the plt step function the result for the age data is shown in figure the empirical cumulative distribution function for discrete quantitative variable is obtained in the same way np sortnutri agey np linspace ( , lennutri age)plt xlabel ('age 'plt ylabel ('fn( )'plt step( ,yplt xlim( min (, max ()plt show (empirical cumulative distribution function indicator |
14,782 | fn( age figure plot of the empirical distribution function for the continuous quantitative feature 'agedata visualization in bivariate setting in this sectionwe present few useful visual aids to explore relationships between two features the graphical representation will depend on the type of the two features two-way plots for two categorical variables comparing barplots for two categorical variables involves introducing subplots to the figure figure visualizes the contingency table of section which cross-tabulates the family status (situationwith the gender of the elderly people it simply shows two barplots next to each other in the same figure male female counts couple family single figure barplot for two categorical variables |
14,783 | the figure was made using the seaborn packagewhich was specifically designed to simplify statistical visualization tasks import seaborn as sns sns countplot ( ='situation 'hue 'gender 'data=nutri hue_order ['male ''female ']palette ['skyblue ','pink ']saturation edgecolor ='black 'plt legend (loc='upper center 'plt xlabel (''plt ylabel ('counts 'plt show ( plots for two quantitative variables we can visualize patterns between two quantitative features using scatterplot this can be done with plt scatter the following code produces scatterplot of 'weightagainst 'heightfor the nutri data scatterplot plt scatter nutri height nutri weight = marker =' 'plt xlabel ('height 'plt ylabel ('weight 'plt show ( weight height figure scatterplot of 'weightagainst 'heightthe next python code illustrates that it is possible to produce highly sophisticated scatter plotssuch as in figure the figure shows the birth weights (massof babies whose mothers smoked (blue trianglesor not (red circlesin additionstraight lines were fitted to the two groupssuggesting that birth weight decreases with age when the mother smokesbut increases when the mother does not smokethe question is whether these trends are statistically significant or due to chance we will revisit this data set later on in the book |
14,784 | urlprefix 'https :/vincentarelbundock github iordatasets /csv/dataname 'massbirthwt csv bwt pd read_csv urlprefix dataname bwt bwt drop('unnamed , #drop unnamed column styles { [' ','red '] ['^','blue ']for in styles grp bwt[bwt smoke ==km, np polyfit (grp age grp bwt fit straight line plt scatter (grp age grp bwt cstyles [ ][ = linewidth = marker styles [ ][ ]plt plot(grp age *grp age '-'color styles [ ][ ]plt xlabel ('age 'plt ylabel ('birth weight ( )'plt legend (['non smokers ','smokers '],prop ={'size ': loc =( , plt show ( non-smokers smokers birth weight ( age figure birth weight against age for smoking and non-smoking mothers plots for one qualitative and one quantitative variable in this settingit is interesting to draw boxplots of the quantitative feature for each level of the categorical feature assuming the variables are structured correctlythe function plt boxplot can be used to produce figure using the following codemales nutri nutri gender ='male 'females nutri nutri gender ='female 'plt boxplot (males coffee females coffee ]notch =true widths =( , plt xlabel ('gender 'plt ylabel ('coffee 'plt xticks ([ , ,'male ','female ']plt show ( |
14,785 | coffee male gender female figure boxplots of quantitative feature 'coffeeas function of the levels of categorical feature 'gendernote that we used different"notched"style boxplot this time further reading the focus in this book is on the mathematical and statistical analysis of dataand for the rest of the book we assume that the data is available in suitable form for analysis howevera large part of practical data science involves the cleaning of datathat isputting it into form that is amenable to analysis with standard software packages standard python modules such as numpy and pandas can be used to reformat rowsrename columnsremove faulty outliersmerge rowsand so on mckinneythe creator of pandasgives many practical case studies in [ effective data visualization techniques are beautifully illustrated in [ exercises before you attempt these exercisesmake sure you have up-to-date versions of the relevant python packagesspecifically matplotlibpandasand seaborn an easy way to ensure this is to update packages via the anaconda navigatoras explained in appendix visit the uci repository the data and download the mushroom data set agaricus-lepiota data using pandasread the data into dataframe called mushroomvia read_csv (ahow many features are in this data set(bwhat are the initial names and types of the features(crename the first feature (index to 'edibilityand the sixth feature (index to 'odor[hintthe column names in pandas are immutableso individual columns cannot be modified directly however it is possible to assign the entire column names list via mushroom columns newcols |
14,786 | (dthe th column lists the various odors of the mushroomsencoded as ' '' 'replace these with the names 'almond''creosote'etc (categories corresponding to each letter can be found on the websitealso replace the 'edibilitycategories 'eand 'pwith 'edibleand 'poisonous(emake contingency table cross-tabulating 'edibilityand 'odor(fwhich mushroom odors should be avoidedwhen gathering mushrooms for consumption(gwhat proportion of odorless mushroom samples were safe to eat change the type and value of variables in the nutri data set according to table and save the data as csv file the modified data should have eight categorical featuresthree floatsand two integer features it frequently happens that table with data needs to be restructured before the data can be analyzed using standard statistical software as an exampleconsider the test scores in table of students before and after specialized tuition table student scores student before after this is not in the standard format described in section in particularthe student scores are divided over two columnswhereas the standard format requires that they are collected in one columne labelled 'scorereformat (by handthe table in standard formatusing three features'score'taking continuous values'time'taking values 'beforeand 'after''student'taking values from to useful methods for reshaping tables in pandas are meltstackand unstack create similar barplot as in figure but now plot the corresponding proportions of males and females in each of the three situation categories that isthe heights of the bars should sum up to for both barplots with the same 'gendervalue [hintseaborn does not have this functionality built ininstead you need to first create contingency table and use matplotlib pyplot to produce the figure + the iris data setmentioned in section contains various featuresincluding 'petal lengthand 'sepal length'of three species of irissetosaversicolorand virginica |
14,787 | (aload the data set into pandas dataframe object (busing matplotlib pyplotproduce boxplots of 'petal lengthfor each the three speciesin one figure (cmake histogram with bins for 'petal length(dproduce similar scatterplot for 'sepal lengthagainst 'petal lengthto that of the left plot in figure note that the points should be colored according to the 'speciesfeature as per the legend in the right plot of the figure (eusing the kdeplot method of the seaborn packagereproduce the right plot of figure where kernel density plots for 'petal lengthare given setosa density sepal length versicolor virginica petal length petal length figure leftscatterplot of 'sepal lengthagainst 'petal lengthrightkernel density estimates of 'petal lengthfor the three species of iris import the data set eustockmarkets from the same website as the iris data set above the data set contains the daily closing prices of four european stock indices during the sfor working days per year (acreate vector of times (working daysfor the stock pricesbetween and with increments of / (breproduce figure [hintuse dictionary to map column names (stock indicesto colors |
14,788 | dax smi cac ftse figure closing stock indices for various european stock markets consider the kasandr data set from the uci machine learning repositorywhich can be downloaded from tar bz this archive file has size of mbso it may take while to download uncompressing the file ( via -zipyields directory de containing two large csv filestest_de csv and train_de csvwith sizes mb and gbrespectively such large data files can still be processed efficiently in pandasprovided there is enough memory the files contain records of user information from kelkoo web logs in germany as well as meta-data on usersoffersand merchants the data sets have attributes and and rowsrespectively the data sets are anonymized via hex strings (aload train_de csv into pandas dataframe object deusing read_csv('train_de csv'delimiter '\ 'if not enough memory is availableload test_de csv instead note that entries are separated here by tabsnot commas time how long it takes for the file to loadusing the time package (it took seconds for train_de csv to load on one of our computers (bhow many unique users and merchants are in this data set visualizing data involving more than two features requires careful designwhich is often more of an art than science (ago to vincent arel-bundocks' website (url given in section and read the orange data set into pandas dataframe object called orange remove its first (unnamedcolumn (bthe data set contains the circumferences of orange trees at various stages in their development find the names of the features (cin pythonimport seaborn and visualize the growth curves (circumference against ageof the treesusing the regplot and facetgrid methods |
14,789 | tatistical earning the purpose of this is to introduce the reader to some common concepts and themes in statistical learning we discuss the difference between supervised and unsupervised learningand how we can assess the predictive performance of supervised learning we also examine the central role that the linear and gaussian properties play in the modeling of data we conclude with section on bayesian learning the required probability and statistics background is given in appendix introduction although structuring and visualizing data are important aspects of data sciencethe main challenge lies in the mathematical analysis of the data when the goal is to interpret the model and quantify the uncertainty in the datathis analysis is usually referred to as statistical learning in contrastwhen the emphasis is on making predictions using large-scale datathen it is common to speak about machine learning or data mining there are two major goals for modeling data to accurately predict some future quantity of interestgiven some observed dataand to discover unusual or interesting patterns in the data to achieve these goalsone must rely on knowledge from three important pillars of the mathematical sciences function approximation building mathematical model for data usually means understanding how one data variable depends on another data variable the most natural way to represent the relationship between variables is via mathematical function or map we usually assume that this mathematical function is not completely knownbut can be approximated well given enough computing power and data thusdata scientists have to understand how best to approximate and represent functions using the least amount of computer processing and memory optimization given class of mathematical modelswe wish to find the best possible model in that class this requires some kind of efficient search or optimization procedure the optimization step can be viewed as process of fitting or calibrating function to observed data this step usually requires knowledge of optimization algorithms and efficient computer coding or programming statistical learning machine learning data mining |
14,790 | probability and statistics in generalthe data used to fit the model is viewed as realization of random process or numerical vectorwhose probability law determines the accuracy with which we can predict future observations thusin order to quantify the uncertainty inherent in making predictions about the futureand the sources of error in the modeldata scientists need firm grasp of probability theory and statistical inference feature response prediction function regression classification loss function supervised and unsupervised learning given an input or feature vector xone of the main goals of machine learning is to predict an output or response variable for examplex could be digitized signature and binary variable that indicates whether the signature is genuine or false another example is where represents the weight and smoking habits of an expecting mother and the birth weight of the baby the data science attempt at this prediction is encoded in mathematical function gcalled the prediction functionwhich takes as an input and outputs guess (xfor (denoted by yfor examplein senseg encompasses all the information about the relationship between the variables and yexcluding the effects of chance and randomness in nature in regression problemsthe response variable can take any real value in contrastwhen can only lie in finite setsay { }then predicting is conceptually the same as classifying the input into one of categoriesand so prediction becomes classification problem we can measure the accuracy of prediction with respect to given response by using some loss function loss( , yin regression setting the usual choice is the squared error loss ( - yin the case of classificationthe zero-one (also written - loss function loss( , { yis often usedwhich incurs loss of whenever the predicted class is not equal to the class later on in this bookwe will encounter various other useful loss functionssuch as the cross-entropy and hinge loss functions (seee the word error is often used as measure of distance between "trueobject and some approximation thereof if is real-valuedthe absolute error | yand the squared error ( - yare both well-established error conceptsas are the norm ky- yk and squared norm ky - yk for vectors the squared error ( - yis just one example of loss function risk it is unlikely that any mathematical function will be able to make accurate predictions for all possible pairs (xyone may encounter in nature one reason for this is thateven with the same input xthe output may be differentdepending on chance circumstances or randomness for this reasonwe adopt probabilistic approach and assume that each pair (xyis the outcome of random pair (xythat has some joint probability density (xywe then assess the predictive performance via the expected lossusually called the riskfor `(ge loss(yg( )( for examplein the classification case with zero-one loss function the risk is equal to the probability of incorrect classification`(gp[ ( )in this contextthe prediction |
14,791 | function is called classifier given the distribution of (xyand any loss functionwe can in principle find the best possible :argming loss(yg( )that yields the smallest risk `:`(gwe will see in that in the classification case with { - and `(gp[ ( )]we have classifier (xargmax ( ) { , - where ( xp[ xis the conditional probability of given as already mentionedfor regression the most widely-used loss function is the squarederror loss in this settingthe optimal prediction function gis often called the regression function the following theorem specifies its exact form regression function theorem optimal prediction function for squared-error loss for the squared-error loss loss( , ( - ) the optimal prediction function gis equal to the conditional expectation of given xg(xe[ xprooflet (xe[ xfor any function gthe squared-error risk satisfies ( ( )) [( (xg(xg( )) ( ( )) [( ( ))( (xg( )) ( (xg( )) ( ( )) [( ( ))( (xg( )) ( ( )) {( (xg( )) [ (xx]in the last equation we used the tower property by the definition of the conditional expectationwe have [ (xx it follows that ( ( )) ( ( )) showing that gyields the smallest squared-error risk one consequence of theorem is thatconditional on xthe (randomresponse can be written as (xe( )( where (xcan be viewed as the random deviation of the response from its conditional mean at this random deviation satisfies ( furtherthe conditional variance of the response at can be written as var (xv (xfor some unknown positive function note thatin generalthe probability distribution of (xis unspecified sincethe optimal prediction function gdepends on the typically unknown joint distribution of (xy)it is not available in practice insteadall that we have available is finite number of (usuallyindependent realizations from the joint density (xywe denote this sample by {( )(xn yn )and call it the training set ( is mnemonic for trainingwith examples it will be important to distinguish between random training set and its (deterministicoutcome {( )(xn yn )we will use the notation for the latter we will also add the subscript in tn when we wish to emphasize the size of the training set our goal is thus to "learnthe unknown gusing the examples in the training set let us denote by gt the best (by some criterionapproximation for gthat we can construct training set |
14,792 | learner supervised learning explanatory variables unsupervised learning supervised and unsupervised learning from note that gt is random function particular outcome is denoted by gt it is often useful to think of teacher-learner metaphorwhereby the function gt is learner who learns the unknown functional relationship gx from the training data we can imagine "teacherwho provides examples of the true relationship between the output yi and the input xi for nand thus "trainsthe learner gt to predict the output of new input xfor which the correct output is not provided by the teacher (is unknownthe above setting is called supervised learningbecause one tries to learn the functional relationship between the feature vector and response in the presence of teacher who provides examples it is common to speak of "explainingor predicting on the basis of xwhere is vector of explanatory variables an example of supervised learning is email spam detection the goal is to train the learner gt to accurately predict whether any future emailas represented by the feature vector xis spam or not the training data consists of the feature vectors of number of different email examples as well as the corresponding labels (spam or not spamfor instancea feature vector could consist of the number of times sales-pitch words like "free""sale"or "miss outoccur within given email as seen from the above discussionmost questions of interest in supervised learning can be answered if we know the conditional pdf ( )because we can then in principle work out the function value (xin contrastunsupervised learning makes no distinction between response and explanatory variablesand the objective is simply to learn the structure of the unknown distribution of the data in other wordswe need to learn (xin this case the guess (xis an approximation of (xand the risk is of the form `(ge lossf ( ) ( ) an example of unsupervised learning is when we wish to analyze the purchasing behaviors of the customers of grocery shop that has total ofsaya hundred items on sale feature vector here could be binary vector { } representing the items bought by customer on visit to the shop ( in the -th position if customer bought item { and otherwisebased on training set { xn }we wish to find any interesting or unusual purchasing patterns in generalit is difficult to know if an unsupervised learner is doing good jobbecause there is no teacher to provide examples of accurate predictions the main methodologies for unsupervised learning include clusteringprincipal component analysisand kernel density estimationwhich will be discussed in in the next three sections we will focus on supervised learning the main supervised learning methodologies are regression and classificationto be discussed in detail in and more advanced supervised learning techniquesincluding reproducing kernel hilbert spacestree methodsand deep learningwill be discussed in and |
14,793 | training and test loss given an arbitrary prediction function git is typically not possible to compute its risk `(gin ( howeverusing the training sample we can approximate `(gvia the empirical (sample averagerisk loss(yi (xi ))( ` (gn = which we call the training loss the training loss is thus an unbiased estimator of the risk (the expected lossfor prediction function gbased on the training data to approximate the optimal prediction function (the minimizer of the risk `( )we first select suitable collection of approximating functions and then take our learner to be the function in that minimizes the training lossthat isggt argmin ` (ggg training loss ( for examplethe simplest and most useful is the set of linear functions of xthat isthe set of all functions bx for some real-valued vector we suppress the superscript when it is clear which function class is used note that minimizing the training loss over all possible functions (rather than over all gdoes not lead to meaningful optimization problemas any function for which (xi yi for all gives minimal training loss in particularfor squared-error lossthe training loss will be unfortunatelysuch functions have poor ability to predict new (that isindependent from pairs of data this poor generalization performance is called overfitting overfitting by choosing function that predicts the training data exactly (and isfor example otherwise)the squared-error training loss is zero minimizing the training loss is not the ultimate goalthe prediction accuracy of new pairs of data is measured by the generalization risk of the learner for fixed training set it is defined as `(ggt loss(yggt ( ))( where (xyis distributed according to (xyin the discrete case the generalization risk is therefore`(ggt , loss(yggt ( ) (xy(replace the sum with an integral for the continuous casethe situation is illustrated in figure where the distribution of (xyis indicated by the red dots the training set (points in the shaded regionsdetermines fixed prediction function shown as straight line three possible outcomes of (xyare shown (black dotsthe amount of loss for each point is shown as the length of the dashed lines the generalization risk is the average loss over all possible pairs (xy)weighted by the corresponding (xygeneralization risk |
14,794 | figure the generalization risk for fixed training set is the weighted-average loss over all possible pairs (xyexpected generalization risk for random training set the generalization risk is thus random variable that depends on (and gif we average the generalization risk over all possible instances of we obtain the expected generalization riske `(ggt loss(yggt ( ))( where (xyin the expectation above is independent of in the discrete casewe have `(ggt , , , ,xn ,yn loss(yggt ( ) (xyf ( (xn yn figure gives an illustration figure the expected generalization risk is the weighted-average loss over all possible pairs (xyand over all training sets for any outcome of the training datawe can estimate the generalization risk without bias by taking the sample average ` (ggt :test sample test loss loss(yi ggt ( )) = ( where {( )( yn )= is so-called test sample the test sample is completely separate from but is drawn in the same way as that isvia independent draws from (xy)for some sample size we call the estimator ( the test loss for random training set we can define ` (ggt similarly it is then crucial to assume that is independent of table summarizes the main definitions and notation for supervised learning |
14,795 | table summary of definitions for supervised learning (xyf ( xt or tn or tn loss( , `(gggg ` ( ` (gggt or gt ggt or gt fixed explanatory (featurevector random explanatory (featurevector fixed (real-valuedresponse random response joint pdf of and yevaluated at (xyconditional pdf of given xevaluated at fixed training data {(xi yi ) nrandom training data {(xi yi ) nmatrix of explanatory variableswith rows > and dim(xfeature columnsone of the features may be the constant vector of response variables ( yn )prediction (guessfunction loss incurred when predicting response with risk for prediction function gthat ise loss(yg( )optimal prediction functionthat isargming `(goptimal prediction function in function class gthat isargmingg `(gtraining loss for prediction function gthat isthe sample average estimate of `(gbased on fixed training sample the same as ` ( )but now for random training sample the learnerargmingg ` (gthat isthe optimal prediction function based on fixed training set and function class we suppress the superscript if the function class is implicit the learnerwhere we have replaced with random training set to compare the predictive performance of various learners in the function class gas measured by the test losswe can use the same fixed training set and test set for all learners when there is an abundance of datathe "overalldata set is usually (randomlydivided into training and test setas depicted in figure we then use the training data to construct various learners ggt ggt and use the test data to select the best (with the smallest test lossamong these learners in this context the test set is called the validation set once the best learner has been chosena third "testset can be used to assess the predictive performance of the best learner the trainingvalidationand test sets can again be obtained from the overall data set via random allocation when the overall data set is of modest sizeit is customary to perform the validation phase (model selectionon the training set onlyusing cross-validation this is the topic of section validation set |
14,796 | figure statistical learning algorithms often require the data to be divided into training and test data if the latter is used for model selectiona third set is needed for testing the performance of the selected model we next consider concrete example that illustrates the concepts introduced so far ( which is depicted by the dashed curve in figure data points true (upolynomial regression model example (polynomial regressionin what followsit will appear that we have arbitrarily replaced the symbols xgg with uhhrespectively the reason for this switch of notation will become clear at the end of the example the data (depicted as dotsin figure are points (ui yi ) drawn from iid random points (ui yi ) nwhere the {ui are uniformly distributed on the interval ( andgiven ui ui the random variable yi has normal distribution with expectation ui and variance ` this is an example of polynomial regression model using squared-error lossthe optimal prediction function (ue[ uis thus figure training data and the optimal polynomial prediction function |
14,797 | to obtain good estimate of (ubased on the training set {(ui yi ) }we minimize the outcome of the training loss ( ) (yi (ui )) ` (hn = ( over suitable set of candidate functions let us take the set of polynomial functions in of order ( : - ( for and parameter vector [ ]this function class contains the best possible (ue[ ufor note that optimization over is parametric optimization problemin that we need to find the best optimization of ( over is not straightforwardunless we notice that ( is linear function in in particularif we map each feature to feature vector [ uu - ]then the right-hand side of ( can be written as the function (xxbwhich is linear in (as well as bthe optimal (uin for then corresponds to the function (xxbin the set of linear functions from to rwhere [ - - ]thusinstead of working with the set of polynomial functions we may prefer to work with the set of linear functions this brings us to very important idea in statistical learningexpand the feature space to obtain linear prediction function let us now reformulate the learning problem in terms of the new explanatory (featurevariables xi [ ui uip- ] it will be convenient to arrange these feature vectors into matrix with rows > > - - ( un unp- collecting the responses {yi into column vector ythe training loss ( can now be written compactly as ky xbk ( to find the optimal learner ( in the class we need to find the minimizer of ( ) argmin ky xbk ( which is called the ordinary least-squares solution as is illustrated in figure to find bwe choose xb to be equal to the orthogonal projection of onto the linear space spanned by the columns of the matrix xthat isxb pywhere is the projection matrix ordinary least-squares projection matrix |
14,798 | xb xb span(xfigure xb is the orthogonal projection of onto the linear space spanned by the columns of the matrix according to theorem the projection matrix is given by xpseudo-inverse normal equations where the matrix xin ( is the pseudo-inverse of if happens to be of full column rank (so that none of the columns can be expressed as linear combination of the other columns)then (xx)- xin any casefrom xb py and px xwe can see that satisfies the normal equationsxxb xpy (px) xy ( this is set of linear equationswhich can be solved very fast and whose solution can be written explicitly asb xy ( figure shows the trained learners for various values of ph ht (ugt (xx> data points true underfit correct overfit ( ( figure training data with fitted curves for and the true cubic polynomial curve for is also plotted (dashed line |
14,799 | we see that for the fitted curve lies closer to the data pointsbut is further away from the dashed true polynomial curveindicating that we overfit the choice (the true cubic polynomialis much better than or indeed (straight lineg each function class gives different learner gt to assess which is betterwe should not simply take the one that gives the smallest training loss we can always get zero training loss by taking nbecause for any set of points there exists polynomial of degree that interpolates all pointsinsteadwe assess the predictive performance of the learners using the test loss ( )computed from test data set if we collect all test feature vectors in matrix and the corresponding test responses in vector thensimilar to ( )the test loss can be written compactly as bk ` (gt ky where is given by ( )using the training data figure shows plot of the test loss against the number of parameters in the vector bthat isp the graph has characteristic "bath-tubshape and is at its lowest for correctly identifying the polynomial order for the true model note that the test lossas an estimate for the generalization risk ( )becomes numerically unreliable after (the graph goes downwhere it should go upthe reader may check that the graph for the training loss exhibits similar numerical instability for large pand in fact fails to numerically decrease to for large pcontrary to what it should do in theory the numerical problems arise from the fact that for large the columns of the (vandermondematrix are of vastly different magnitudes and so floating point errors quickly become very large finallyobserve that the lower bound for the test loss is here around which corresponds to an estimate of the minimal (squared-errorrisk ` test loss number of parameters figure test loss as function of the number of parameters of the model this script shows how the training data were generated and plotted in python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.