Python Code For Artificial Intelligence: Foundations Of Computational .

1y ago
25 Views
5 Downloads
1.37 MB
312 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Jayda Dunning
Transcription

1Python code for ArtificialIntelligence: Foundations ofComputational AgentsDavid L. Poole and Alan K. MackworthVersion 0.9.4 of June 2, 2022.http://aipython.org http://artint.info David L Poole and Alan K Mackworth 2017-2021.All code is licensed under a Creative Commons Attribution-NonCommercialShareAlike 4.0 International License. See: eed.en USThis document and all the code can be downloaded fromhttp://artint.info/AIPython/ or from http://aipython.orgThe authors and publisher of this book have used their best efforts in preparing this book. These efforts include the development, research and testing ofthe theories and programs to determine their effectiveness. The authors andpublisher make no warranty of any kind, expressed or implied, with regard tothese programs or the documentation contained in this book. The author andpublisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or useof these programs.http://aipython.orgVersion 0.9.4June 2, 2022

ContentsContents123Python for Artificial Intelligence1.1Why Python? . . . . . . . . . . . . . . . . . . . . . . . . . .1.2Getting Python . . . . . . . . . . . . . . . . . . . . . . . . .1.3Running Python . . . . . . . . . . . . . . . . . . . . . . . .1.4Pitfalls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1.5Features of Python . . . . . . . . . . . . . . . . . . . . . . .1.5.1 Lists, Tuples, Sets, Dictionaries and Comprehensions1.5.2 Functions as first-class objects . . . . . . . . . . . . . .1.5.3 Generators and Coroutines . . . . . . . . . . . . . . .1.6Useful Libraries . . . . . . . . . . . . . . . . . . . . . . . . .1.6.1 Timing Code . . . . . . . . . . . . . . . . . . . . . . .1.6.2 Plotting: Matplotlib . . . . . . . . . . . . . . . . . . .1.7Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1.7.1 Display . . . . . . . . . . . . . . . . . . . . . . . . . . .1.7.2 Argmax . . . . . . . . . . . . . . . . . . . . . . . . . .1.7.3 Probability . . . . . . . . . . . . . . . . . . . . . . . . .1.7.4 Dictionary Union . . . . . . . . . . . . . . . . . . . . .1.8Testing Code . . . . . . . . . . . . . . . . . . . . . . . . . . .Agents and Control2.1Representing Agents and Environments2.2Paper buying agent and environment .2.2.1 The Environment . . . . . . . . . .2.2.2 The Agent . . . . . . . . . . . . . .3.999101111111214151516161618191919.2121222224

4Contents.25252526282930Searching for Solutions3.1Representing Search Problems . . . . . . . .3.1.1 Explicit Representation of Search Graph3.1.2 Paths . . . . . . . . . . . . . . . . . . . .3.1.3 Example Search Problems . . . . . . . .3.2Generic Searcher and Variants . . . . . . . . .3.2.1 Searcher . . . . . . . . . . . . . . . . . .3.2.2 Frontier as a Priority Queue . . . . . . .3.2.3 A Search . . . . . . . . . . . . . . . . .3.2.4 Multiple Path Pruning . . . . . . . . . .3.3Branch-and-bound Search . . . . . . . . . . 777981818284.87879092932.33452.2.3 Plotting . . . . .Hierarchical Controller2.3.1 Environment . .2.3.2 Body . . . . . . .2.3.3 Middle Layer . .2.3.4 Top Layer . . . .2.3.5 Plotting . . . . .Reasoning with Constraints4.1Constraint Satisfaction Problems . . . . . . . . . . . . . .4.1.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . .4.1.2 Constraints . . . . . . . . . . . . . . . . . . . . . . .4.1.3 CSPs . . . . . . . . . . . . . . . . . . . . . . . . . . .4.1.4 Examples . . . . . . . . . . . . . . . . . . . . . . . .4.2A Simple Depth-first Solver . . . . . . . . . . . . . . . . .4.3Converting CSPs to Search Problems . . . . . . . . . . . .4.4Consistency Algorithms . . . . . . . . . . . . . . . . . . .4.4.1 Direct Implementation of Domain Splitting . . . . .4.4.2 Domain Splitting as an interface to graph searching4.5Solving CSPs using Stochastic Local Search . . . . . . . .4.5.1 Any-conflict . . . . . . . . . . . . . . . . . . . . . . .4.5.2 Two-Stage Choice . . . . . . . . . . . . . . . . . . . .4.5.3 Updatable Priority Queues . . . . . . . . . . . . . .4.5.4 Plotting Runtime Distributions . . . . . . . . . . . .4.5.5 Testing . . . . . . . . . . . . . . . . . . . . . . . . . .4.6Discrete Optimization . . . . . . . . . . . . . . . . . . . .4.6.1 Branch-and-bound Search . . . . . . . . . . . . . . .Propositions and Inference5.1Representing Knowledge Bases .5.2Bottom-up Proofs (with askables)5.3Top-down Proofs (with askables)5.4Debugging and Explanation . . .http://aipython.org.Version 0.9.4.June 2, 2022

Contents5.567895Assumables . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97Planning with Certainty6.1Representing Actions and Planning Problems . . .6.1.1 Robot Delivery Domain . . . . . . . . . . . .6.1.2 Blocks World . . . . . . . . . . . . . . . . . .6.2Forward Planning . . . . . . . . . . . . . . . . . . .6.2.1 Defining Heuristics for a Planner . . . . . . .6.3Regression Planning . . . . . . . . . . . . . . . . .6.3.1 Defining Heuristics for a Regression Planner6.4Planning as a CSP . . . . . . . . . . . . . . . . . . .6.5Partial-Order Planning . . . . . . . . . . . . . . . .101101102104106109111113114117Supervised Machine Learning7.1Representations of Data and Predictions . . . . .7.1.1 Creating Boolean Conditions from Features7.1.2 Evaluating Predictions . . . . . . . . . . . .7.1.3 Creating Test and Training Sets . . . . . . .7.1.4 Importing Data From File . . . . . . . . . .7.1.5 Augmented Features . . . . . . . . . . . . .7.2Generic Learner Interface . . . . . . . . . . . . .7.3Learning With No Input Features . . . . . . . . .7.3.1 Evaluation . . . . . . . . . . . . . . . . . . .7.4Decision Tree Learning . . . . . . . . . . . . . . .7.5Cross Validation and Parameter Tuning . . . . .7.6Linear Regression and Classification . . . . . . .7.6.1 Batched Stochastic Gradient Descent . . . .7.7Boosting . . . . . . . . . . . . . . . . . . . . . . .7.7.1 Gradient Tree Boosting . . . . . . . . . . . eural Networks and Deep Learning8.1Layers . . . . . . . . . . . . . .8.2Feedforward Networks . . . . .8.3Improved Optimization . . . .8.3.1 Momentum . . . . . . . .8.3.2 RMS-Prop . . . . . . . . .8.4Dropout . . . . . . . . . . . . .8.4.1 Examples . . . . . . . . .163163166168168169170171Reasoning Under Uncertainty9.1Representing Probabilistic Models . .9.2Representing Factors . . . . . . . . . .9.3Conditional Probability Distributions9.3.1 Logistic Regression . . . . . . . .9.3.2 Noisy-or . . . . . . . . . . . . . .177177178179180181http://aipython.org.Version 0.9.4.June 2, 2022

6Contents9.3.3 Tabular Factors . . . . . . . . . . . . . . . . . . .Graphical Models . . . . . . . . . . . . . . . . . . . . .9.4.1 Example Belief Networks . . . . . . . . . . . . .9.5Inference Methods . . . . . . . . . . . . . . . . . . . .9.6Recursive Conditioning . . . . . . . . . . . . . . . . .9.7Variable Elimination . . . . . . . . . . . . . . . . . . .9.8Stochastic Simulation . . . . . . . . . . . . . . . . . . .9.8.1 Sampling from a discrete distribution . . . . . .9.8.2 Sampling Methods for Belief Network Inference9.8.3 Rejection Sampling . . . . . . . . . . . . . . . . .9.8.4 Likelihood Weighting . . . . . . . . . . . . . . .9.8.5 Particle Filtering . . . . . . . . . . . . . . . . . .9.8.6 Examples . . . . . . . . . . . . . . . . . . . . . .9.8.7 Gibbs Sampling . . . . . . . . . . . . . . . . . . .9.8.8 Plotting Behaviour of Stochastic Simulators . . .9.9Hidden Markov Models . . . . . . . . . . . . . . . . .9.9.1 Exact Filtering for HMMs . . . . . . . . . . . . .9.9.2 Localization . . . . . . . . . . . . . . . . . . . . .9.9.3 Particle Filtering for HMMs . . . . . . . . . . . .9.9.4 Generating Examples . . . . . . . . . . . . . . .9.10 Dynamic Belief Networks . . . . . . . . . . . . . . . .9.10.1 Representing Dynamic Belief Networks . . . . .9.10.2 Unrolling DBNs . . . . . . . . . . . . . . . . . . .9.10.3 DBN Filtering . . . . . . . . . . . . . . . . . . . .9.11 Causal Models . . . . . . . . . . . . . . . . . . . . . . 424711 Learning with Uncertainty11.1 K-means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11.2 EM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .25125125512 Reinforcement Learning12.1 Representing Agents and Environments . . . .12.1.1 Simulating an environment from an MDP12.1.2 Simple Game . . . . . . . . . . . . . . . .12.1.3 Evaluation and Plotting . . . . . . . . . .2612612622632659.410 Planning with Uncertainty10.1 Decision Networks . . . . . . . . . . . . . . . . . . .10.1.1 Example Decision Networks . . . . . . . . . .10.1.2 Recursive Conditioning for decision networks10.1.3 Variable elimination for decision networks . .10.2 Markov Decision Processes . . . . . . . . . . . . . .10.2.1 Value Iteration . . . . . . . . . . . . . . . . . .10.2.2 Showing Grid MDPs . . . . . . . . . . . . . . .10.2.3 Asynchronous Value Iteration . . . . . . . . . .http://aipython.orgVersion 0.9.4.June 2, 2022

Contents712.2Q Learning . . . . . . . . . . . . . . . .12.2.1 Testing Q-learning . . . . . . . .12.3 Q-leaning with Experience Replay . .12.4 Model-based Reinforcement Learner .12.5 Reinforcement Learning with Features12.5.1 Representing Features . . . . . .12.5.2 Feature-based RL learner . . . .12.5.3 Experience Replay . . . . . . . .13 Multiagent Systems13.1 Minimax . . . . . . . . . . . . . .13.1.1 Creating a two-player game13.1.2 Minimax and α-β Pruning .13.2 Multiagent Learning . . . . . . .14 Relational Learning14.1 Collaborative Filtering . . . .14.1.1 Alternative Formulation14.1.2 Plotting . . . . . . . . .14.1.3 Creating Rating Sets . 8298299.15 Version rgVersion 0.9.4June 2, 2022

Chapter 1Python for Artificial Intelligence1.1Why Python?We use Python because Python programs can be close to pseudo-code. It isdesigned for humans to read.Python is reasonably efficient. Efficiency is usually not a problem for smallexamples. If your Python code is not efficient enough, a general procedureto improve it is to find out what is taking most the time, and implement justthat part more efficiently in some lower-level language. Most of these lowerlevel languages interoperate with Python nicely. This will result in much lessprogramming and more efficient code (because you will have more time tooptimize) than writing everything in a low-level language. You will not haveto do that for the code here if you are using it for course projects.1.2Getting PythonYou need Python 3 (http://python.org/) and matplotlib (http://matplotlib.org/) that runs with Python 3. This code is not compatible with Python 2 (e.g.,with Python 2.7).Download and istall the latest Python 3 release from http://python.org/.This should also install pip3. You can install matplotlib usingpip3 install matplotlibin a terminal shell (not in Python). That should “just work”. If not, try usingpip instead of pip3.The command python or python3 should then start the interactive pythonshell. You can quit Python with a control-D or with quit().9

101. Python for Artificial IntelligenceTo upgrade matplotlib to the latest version (which you should do if youinstall a new version of Python) do:pip3 install --upgrade matplotlibWe recommend using the enhanced interactive python ipython (http://ipython.org/). To install ipython after you have installed python do:pip3 install ipython1.3Running PythonWe assume that everything is done with an interactive Python shell. You caneither do this with an IDE, such as IDLE that comes with standard Pythondistributions, or just running ipython3 (or perhaps just ipython) from a shell.Here we describe the most simple version that uses no IDE. If you download the zip file, and cd to the “aipython” folder where the .py files are, youshould be able to do the following, with user input following : . The firstipython3 command is in the operating system shell (note that the -i is important to enter interactive mode), with user input in bold:ipython -i searchGeneric.pyPython 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 05:52:31)Type 'copyright', 'credits' or 'license' for more informationIPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.Testing problem 1:7 paths have been expanded and 4 paths remain in the frontierPath found: a -- b -- c -- d -- gPassed unit testIn [1]: searcher2 AStarSearcher(searchProblem.acyclic delivery problem) #A*In [2]: searcher2.search() # find first path16 paths have been expanded and 5 paths remain in the frontierOut[2]: o103 -- o109 -- o119 -- o123 -- r123In [3]: searcher2.search() # find next path21 paths have been expanded and 6 paths remain in the frontierOut[3]: o103 -- b3 -- b4 -- o109 -- o119 -- o123 -- r123In [4]: searcher2.search() # find next path28 paths have been expanded and 5 paths remain in the frontierOut[4]: o103 -- b3 -- b1 -- b2 -- b4 -- o109 -- o119 -- o123 -- r123In [5]: searcher2.search() # find next pathNo (more) solutions. Total of 33 paths expanded.http://aipython.orgVersion 0.9.4June 2, 2022

1.4. Pitfalls11In [6]:You can then interact at the last prompt.There are many textbooks for Python. The best source of information aboutpython is https://www.python.org/. We will be using Python 3; please download the latest release. The documentation is at https://docs.python.org/3/.The rest of this chapter is about what is special about the code for AI tools.We will only use the Standard Python Library and matplotlib. All of the exercises can be done (and should be done) without using other libraries; the aimis for you to spend your time thinking about how to solve the problem ratherthan searching for pre-existing solutions.1.4PitfallsIt is important to know when side effects occur. Often AI programs considerwhat would happen or what may have happened. In many such cases, wedon’t want side effects. When an agent acts in the world, side effects are appropriate.In Python, you need to be careful to understand side effects. For example,the inexpensive function to add an element to a list, namely append, changes thelist. In a functional language like Haskell or Lisp, adding a new element to alist, without changing the original list, is a cheap operation. For example if x isa list containing n elements, adding an extra element to the list in Python (usingappend) is fast, but it has the side effect of changing the list x. To construct a newlist that contains the elements of x plus a new element, without changing thevalue of x, entails copying the list, or using a different representation for lists.In the searching code, we will use a different representation for lists for thisreason.1.5Features of Python1.5.1 Lists, Tuples, Sets, Dictionaries and ComprehensionsWe make extensive uses of lists, tuples, sets and dictionaries (dicts). One of the nice features of Python is the use of list comprehensions (andalso tuple, set and dictionary comprehensions).(fe for e in iter if cond)enumerates the values fe for each e in iter for which cond is true. The “if cond”part is optional, but the “for” and “in” are not optional. Here e has to be avariable, iter is an iterator, which can generate a stream of data, such as a list,a set, a range object (to enumerate integers between ranges) or a file. condhttp://aipython.orgVersion 0.9.4June 2, 2022

121. Python for Artificial Intelligenceis an expression that evaluates to either True or False for each e, and fe is anexpression that will be evaluated for each value of e for which cond returnsTrue.The result can go in a list or used in another iteration, or can be calleddirectly using next. The procedure next takes an iterator returns the next element (advancing the iterator) and raises a StopIteration exception if there isno next element. The following shows a simple example, where user input isprepended with [e*e for e in range(20) if e%2 0][0, 4, 16, 36, 64, 100, 144, 196, 256, 324] a (e*e for e in range(20) if e%2 0) next(a)0 next(a)4 next(a)16 list(a)[36, 64, 100, 144, 196, 256, 324] next(a)Traceback (most recent call last):File " stdin ", line 1, in module StopIterationNotice how list(a) continued on the enumeration, and got to the end of it.Comprehensions can also be used for dictionaries. The following code creates an index for list a: a ["a","f","bar","b","a","aaaaa"] ind {a[i]:i for i in range(len(a))} ind{'a': 4, 'f': 1, 'bar': 2, 'b': 3, 'aaaaa': 5} ind['b']3which means that 'b' is the 3rd element of the list.The assignment of ind could have also be written as: ind {val:i for (i,val) in enumerate(a)}where enumerate returns an iterator of (index, value) pairs.1.5.2 Functions as first-class objectsPython can create lists and other data structures that contain functions. Thereis an issue that tricks many newcomers to Python. For a local variable in afunction, the function uses the last value of the variable when the function ishttp://aipython.orgVersion 0.9.4June 2, 2022

1.5. Features of Python13called, not the value of the variable when the function was defined (this is called“late binding”). This means if you want to use the value a variable has whenthe function is created, you need to save the current value of that variable.Whereas Python uses “late binding” by default, the alternative that newcomersoften expect is “early binding”, where a function uses the value a variable hadwhen the function was defined, can be easily implemented.Consider the following programs designed to create a list of 5 functions,where the ith function in the list is meant to add i to its argument:1pythonDemo.py — Some tricky examples1112131415fun list1 []for i in range(5):def fun1(e):return e ifun list1.append(fun1)161718192021fun list2 []for i in range(5):def fun2(e,iv i):return e ivfun list2.append(fun2)2223fun list3 [lambda e: e i for i in range(5)]2425fun list4 [lambda e,iv i: e iv for i in range(5)]2627i 56Try to predict, and then test to see the output, of the output of the followingcalls, remembering that the function uses the latest value of any variable thatis not bound in the function call:pythonDemo.py — (continued)29303132333435# in Shell do## ipython -i pythonDemo.py# Try these (copy text after the comment symbol and paste in the Pythonprompt):# print([f(10) for f in fun list1])# print([f(10) for f in fun list2])# print([f(10) for f in fun list3])# print([f(10) for f in fun list4])In the first for-loop, the function fun uses i, whose value is the last value it wasassigned. In the second loop, the function fun2 uses iv. There is a separate ivvariable for each function, and its value is the value of i when the function wasdefined. Thus fun1 uses late binding, and fun2 uses early binding. fun list31 Numbered lines are Python code available in the code-directory, aipython. The name ofthe file is given in the gray text above the listing. The numbers correspond to the line numbersin that file.http://aipython.orgVersion 0.9.4June 2, 2022

141. Python for Artificial Intelligenceand fun list4 are equivalent to the first two (except fun list4 uses a different ivariable).One of the advantages of using the embedded definitions (as in fun1 andfun2 above) over the lambda is that is it possible to add a doc string, whichis the standard for documenting functions in Python, to the embedded definitions.1.5.3 Generators and CoroutinesPython has generators which can be used for a form of coroutines.The yield command returns a value that is obtained with next. It is typically used to enumerate the values for a for loop or in generators. (The yieldcommand can also be used for coroutines, but we only us it for genertors inAIPython.)A version of the built-in range, with 2 or 3 arguments (and positive steps)can be implemented as:pythonDemo.py — (continued)373839404142434445def myrange(start, stop, step 1):"""enumerates the values from start in steps of size step that areless than stop."""assert step 0, "only positive steps implemented in myrange"i startwhile i stop:yield ii e(2,30,3)))Note that the built-in range is unconventional in how it handles a single argument, as the single argument acts as the second argument of the function.Note also that the built-in range also allows for indexing (e.g., range(2, 30, 3)[2]returns 8), which the above implementation does not. However myrange alsoworks for floats, which the built-in range does not.Exercise 1.1 Implement a version of myrange that acts like the built-in versionwhen there is a single argument. (Hint: make the second argument have a defaultvalue that can be recognized in the function.)Yield can be used to generate the same sequence of values as in the exampleof Section 1.5.1:pythonDemo.py — (continued)495051525354def ga(n):"""generates square of even nonnegative integers less than n"""for e in range(n):if e%2 0:yield e*ea ga(20)http://aipython.orgVersion 0.9.4June 2, 2022

1.6. Useful Libraries15The sequence of next(a), and list(a) gives exactly the same results as the comprehension in Section 1.5.1.It is straightforward to write a version of the built-in enumerate. Let’s call itmyenumerate:pythonDemo.py — (continued)565758def myenumerate(enum):for i in range(len(enum)):yield i,enum[i]Exercise 1.2 Write a version of enumerate where the only iteration is “for val inenum”. Hint: keep track of the index.1.6Useful Libraries1.6.1 Timing CodeIn order to compare algorithms, we often want to compute how long a programtakes; this is called the runtime of the program. The most straightforward wayto compute runtime is to use time.perf counter(), as in:import timestart time time.perf counter()compute for a while()end time time.perf counter()print("Time:", end time - start time, "seconds")Note that time.perf counter() measures clock time; so this should be donewithout user interaction between the calls. On the console, you should do:start time time.perf counter(); compute for a while(); end time time.perf counter()If this time is very small (say less than 0.2 second), it is probably very inaccurate, and it may be better to run your code many times to get a more accurate count. For this you can use timeit (https://docs.python.org/3/library/timeit.html). To use timeit to time the call to foo.bar(aaa) use:import timeittime timeit.timeit("foo.bar(aaa)",setup "from main import foo,aaa", number 100)The setup is needed so that Python can find the meaning of the names in thestring that is called. This returns the number of seconds to execute foo.bar(aaa)100 times. The variable number should be set so that the runtime is at least 0.2seconds.You should not trust a single measurement as that can be confounded byinterference from other processes. timeit.repeat can be used for running timita few (say 3) times. Usually the minimum time is the one to report, but youshould be explicit and explain what you are reporting.http://aipython.orgVersion 0.9.4June 2, 2022

161. Python for Artificial Intelligence1.6.2 Plotting: MatplotlibThe standard plotting for Python is matplotlib (http://matplotlib.org/). Wewill use the most basic plotting using the pyplot interface.Here is a simple example that uses everything we will use.pythonDemo.py — (continued)60import matplotlib.pyplot as plt616263646566676869707172def myplot(minv,maxv,step,fun1,fun2):plt.ion() # make it interactiveplt.xlabel("The x axis")plt.ylabel("The y axis")plt.xscale('linear') # Makes a 'log' or 'linear' scalexvalues range(minv,maxv,step)plt.plot(xvalues,[fun1(x) for x in xvalues],label "The first fun")plt.plot(xvalues,[fun2(x) for x in xvalues], linestyle '--',color 'k',label fun2. doc ) # use the doc string of the functionplt.legend(loc "upper right") # display the legend73747576777879def slin(x):"""y 2x 7"""return 2*x 7def sqfun(x):"""y (x-40)ˆ2/10-20"""return (x-40)**2/10-208081828384858687888990##########Try the following:from pythonDemo import myplot, slin, sqfunimport matplotlib.pyplot as pltmyplot(0,100,1,slin,sqfun)plt.legend(loc "best")import mathplt.plot([41 40*math.cos(th/10) for th in range(50)],[100 100*math.sin(th/10) for th in log')At the end of the code are some commented-out commands you should try ininteractive mode. Cut from the file and paste into Python (and remember toremove the comments symbol and leading space).1.7Utilities1.7.1 DisplayIn this distribution, to keep things simple and to only use standard Python, weuse a text-oriented tracing of the code. A graphical depiction of the code couldhttp://aipython.orgVersion 0.9.4June 2, 2022

1.7. Utilities17override the definition of display (but we leave it as a project).The method self .display is used to trace the program. Any callself .display(level, to print . . . )where the level is less than or equal to the value for max display level will beprinted. The to print . . . can be anything that is accepted by the built-in print(including any keyword arguments).The definition of display is:display.py — A simple way to trace the intermediate steps of algorithms.1112131415class Displayable(object):"""Class that uses 'display'.The amount of detail is controlled by max display level"""max display level 1 # can be overridden in subclasses161718192021222324def display(self,level,*args,**nargs):"""print the arguments if level is less than or equal to thecurrent max display level.level is an integer.the other arguments are whatever arguments print can take."""if level self.max display level:print(*args, **nargs) ##if error you are using Python2 notPython3Note that args gets a tuple of the positional arguments, and nargs gets a dictionary of the keyword arguments). This will not work in Python 2, and will givean error.Any class that wants to use display can be made a subclass of Displayable.To change the maximum display level to say 3, for a class do:Classname.max display level 3which will make calls to display in that class print when the value of level is lessthan-or-equal to 3. The default display level is 1. It can also be changed forindividual objects (the object value overrides the class value).The value of max display level by convention is:0 display nothing1 display solutions (nothing that happens repeatedly)2 also display the values as they change (little detail through a loop)3 also display more details4 and above even more detailhttp://aipython.orgVersion 0.9.4June 2, 2022

181. Python for Artificial IntelligenceIn order to implement more sophisticated visualizations of the algorithm,we add a visualize “decorator” to the methods to be visualized. The followingcode ignores the decorator:display.py — (continued)2627282930def visualize(func):"""A decorator for algorithms that do interactive visualization.Ignored here."""return func1.7.2 ArgmaxPython has a built-in max function that takes a generator (or a list or set) and returns the maximum value. The argmax method returns the index of an elementthat has the maximum value. If there are multiple elements with the maximum value, one if the indexes to that value is returned at random. argmaxeassumes an enumeration; a generator of (element, value) pairs, as for exampleis generated by the built-in enumerate(list) for lists or dict.items() for dicts.utilities.py — AIPython useful utilities1112import randomimport math13141516171819202122232425def argmaxall(gen):"""gen is a generator of (element,value) pairs, where value is a real.argmaxall returns a list of all of the elements with maximal value."""maxv -math.inf# negative infinitymaxvals []# list of maximal elementsfor (e,v) in gen:if v maxv:maxvals,maxv [e], velif v maxv:maxvals.append(e)return maxvals26272829303132def argmaxe(gen):"""gen is a generator of (element,value) pairs, where value is a real.argmaxe returns an element with maximal value.If there are multiple elements with the max value, one is returned atrandom."""return random.choice(argmaxall(gen))3334353637def argmax(lst):"""returns maximum index in a list"""return argmaxe(enumerate(lst))# Try:http://aipython.orgVersion 0.9.4June 2, 2022

1.8. Testing Code3819# argmax([1,6,3,77,3,55,23])394041424344def argmaxd(dct):"""returns the arx max of a dictionary dct"""return argmaxe(dct.items())# Try:# arxmaxd({2:5,5:9,7:7})Exercise 1.3 Change argmax to have an optional argument that

Python for Artificial Intelligence 1.1 Why Python? We use Python because Python programs can be close to pseudo-code. It is designed for humans to read. Python is reasonably efficient. Efficiency is usually not a problem for small examples. If your Python code is not efficient enough, a general procedure

Related Documents:

Python 2 versus Python 3 - the great debate Installing Python Setting up the Python interpreter About virtualenv Your first virtual environment Your friend, the console How you can run a Python program Running Python scripts Running the Python interactive shell Running Python as a service Running Python as a GUI application How is Python code .

Python Programming for the Absolute Beginner Second Edition. CONTENTS CHAPTER 1 GETTING STARTED: THE GAME OVER PROGRAM 1 Examining the Game Over Program 2 Introducing Python 3 Python Is Easy to Use 3 Python Is Powerful 3 Python Is Object Oriented 4 Python Is a "Glue" Language 4 Python Runs Everywhere 4 Python Has a Strong Community 4 Python Is Free and Open Source 5 Setting Up Python on .

Python is readable 5 Python is complete—"batteries included" 6 Python is cross-platform 6 Python is free 6 1.3 What Python doesn't do as well 7 Python is not the fastest language 7 Python doesn't have the most libraries 8 Python doesn't check variable types at compile time 8 1.4 Why learn Python 3? 8 1.5 Summary 9

Bruksanvisning för bilstereo . Bruksanvisning for bilstereo . Instrukcja obsługi samochodowego odtwarzacza stereo . Operating Instructions for Car Stereo . 610-104 . SV . Bruksanvisning i original

Introduction to basic Python Contents 1. Installing Python 2. How to run Python code 3. How to write Python code 4. How to troubleshoot Python code 5. Where to go to learn more Python is an astronomer's secret weapon. With Python, the process of visualizing, processing, and interacting with data is made extremely simple.

site "Python 2.x is legacy, Python 3.x is the present and future of the language". In addition, "Python 3 eliminates many quirks that can unnecessarily trip up beginning programmers". However, note that Python 2 is currently still rather widely used. Python 2 and 3 are about 90% similar. Hence if you learn Python 3, you will likely

There are currently two versions of Python in use; Python 2 and Python 3. Python 3 is not backward compatible with Python 2. A lot of the imported modules were only available in Python 2 for quite some time, leading to a slow adoption of Python 3. However, this not really an issue anymore. Support for Python 2 will end in 2020.

BIOGRAPHIES James Brown b. 3 May 1928, Barnwell, South Carolina, USA. Brown claims he was born in 1933 in Macon, Georgia. "The Hardest Working Man In