1. Homepage
  2. Programming
  3. CS 188 Introduction to Artificial Intelligence - Project 3: Reinforcement Learning

CS 188 Introduction to Artificial Intelligence - Project 3: Reinforcement Learning

Engage in a Conversation
BerkeleyCS188Introduction to Artificial IntelligenceReinforcement LearningPythonValue IterationQ-LearningEpsilon Greedy

Project 3: Reinforcement Learning

Due: Thursday, October 10th, 11:59 PM PT.

TABLE OF CONTENTS


Introduction

In this project, you will implement value iteration and Q-learning. You will test your agents first on Gridworld (from class), then apply them to a simulated robot controller (Crawler) and Pacman. CourseNana.COM

As in previous projects, this project includes an autograder for you to grade your solutions on your machine. This can be run on all questions with the command: CourseNana.COM

python autograder.py

It can be run for one particular question, such as q2, by: CourseNana.COM

python autograder.py -q q2

It can be run for one particular test by commands of the form: CourseNana.COM

python autograder.py -t test_cases/q2/1-bridge-grid

The code for this project contains the following files, available as a zip archive CourseNana.COM

Files you'll edit:
valueIterationAgents.pyA value iteration agent for solving known MDPs.
qlearningAgents.pyQ-learning agents for Gridworld, Crawler and Pacman.
analysis.pyA file to put your answers to questions given in the project.
Files you might want to look at:
mdp.pyDefines methods on general MDPs.
learningAgents.pyDefines the base classes ValueEstimationAgent and QLearningAgent, which your agents will extend.
util.pyUtilities, including util.Counter, which is particularly useful for Q-learners.
gridworld.pyThe Gridworld implementation.
featureExtractors.pyClasses for extracting features on (state, action) pairs. Used for the approximate Q-learning agent (in qlearningAgents.py).
Supporting files you can ignore:
environment.pyAbstract class for general reinforcement learning environments. Used by gridworld.py.
graphicsGridworldDisplay.pyGridworld graphical display.
graphicsUtils.pyGraphics utilities.
textGridworldDisplay.pyPlug-in for the Gridworld text interface.
crawler.pyThe crawler code and test harness. You will run this but not edit it.
graphicsCrawlerDisplay.pyGUI for the crawler robot.
autograder.pyProject autograder
testParser.pyParses autograder test and solution files
testClasses.pyGeneral autograding test classes
test_cases/Directory containing the test cases for each question
reinforcementTestClasses.pyProject 3 specific autograding test classes

Files to Edit and Submit: You will fill in portions of valueIterationAgents.pyqlearningAgents.py, and analysis.py during the assignment. Once you have completed the assignment, you will submit these files to Gradescope (for instance, you can upload all .py files in the folder). Please do not change the other files in this distribution. CourseNana.COM

Evaluation: Your code will be autograded for technical correctness. Please do not change the names of any provided functions or classes within the code, or you will wreak havoc on the autograder. However, the correctness of your implementation – not the autograder’s judgements – will be the final judge of your score. If necessary, we will review and grade assignments individually to ensure that you receive due credit for your work. CourseNana.COM

Academic Dishonesty: We will be checking your code against other submissions in the class for logical redundancy. If you copy someone else’s code and submit it with minor changes, we will know. These cheat detectors are quite hard to fool, so please don’t try. We trust you all to submit your own work only; please don’t let us down. If you do, we will pursue the strongest consequences available to us. CourseNana.COM

Getting Help: You are not alone! If you find yourself stuck on something, contact the course staff for help. Office hours, section, and the discussion forum are there for your support; please use them. If you can’t make our office hours, let us know and we will schedule more. We want these projects to be rewarding and instructional, not frustrating and demoralizing. But, we don’t know when or how to help unless you ask. CourseNana.COM

Discussion: Please be careful not to post spoilers. CourseNana.COM


MDPs

To get started, run Gridworld in manual control mode, which uses the arrow keys: CourseNana.COM

python gridworld.py -m

You will see the two-exit layout from class. The blue dot is the agent. Note that when you press up, the agent only actually moves north 80% of the time. Such is the life of a Gridworld agent! CourseNana.COM

You can control many aspects of the simulation. A full list of options is available by running: CourseNana.COM

python gridworld.py -h

The default agent moves randomly CourseNana.COM

python gridworld.py -g MazeGrid

You should see the random agent bounce around the grid until it happens upon an exit. Not the finest hour for an AI agent. CourseNana.COM

Note: The Gridworld MDP is such that you first must enter a pre-terminal state (the double boxes shown in the GUI) and then take the special ‘exit’ action before the episode actually ends (in the true terminal state called TERMINAL_STATE, which is not shown in the GUI). If you run an episode manually, your total return may be less than you expected, due to the discount rate (-d to change; 0.9 by default). CourseNana.COM

Look at the console output that accompanies the graphical output (or use -t for all text). You will be told about each transition the agent experiences (to turn this off, use -q). CourseNana.COM

As in Pacman, positions are represented by (x, y) Cartesian coordinates and any arrays are indexed by [x][y], with 'north' being the direction of increasing y, etc. By default, most transitions will receive a reward of zero, though you can change this with the living reward option (-r). CourseNana.COM


Question 1 (5 points): Value Iteration

Recall the value iteration state update equation: CourseNana.COM

𝑉𝑘+1(𝑠)max𝑎𝑠𝑇(𝑠,𝑎,𝑠)[𝑅(𝑠,𝑎,𝑠)+𝛾𝑉𝑘(𝑠)] CourseNana.COM

Write a value iteration agent in ValueIterationAgent, which has been partially specified for you in valueIterationAgents.py. Your value iteration agent is an offline planner, not a reinforcement learning agent, and so the relevant training option is the number of iterations of value iteration it should run (option -i) in its initial planning phase. ValueIterationAgent takes an MDP on construction and runs value iteration for the specified number of iterations before the constructor returns. CourseNana.COM

Value iteration computes 𝑘-step estimates of the optimal values, 𝑉𝑘. In addition to runValueIteration, implement the following methods for ValueIterationAgent using 𝑉𝑘: CourseNana.COM

  • computeActionFromValues(state) computes the best action according to the value function given by self.values.
  • computeQValueFromValues(state, action) returns the Q-value of the (state, action) pair given by the value function given by self.values.

These quantities are all displayed in the GUI: values are numbers in squares, Q-values are numbers in square quarters, and policies are arrows out from each square. CourseNana.COM

Important: Use the “batch” version of value iteration where each vector 𝑉𝑘 is computed from a fixed vector 𝑉𝑘1 (like in lecture), not the “online” version where one single weight vector is updated in place. This means that when a state’s value is updated in iteration 𝑘 based on the values of its successor states, the successor state values used in the value update computation should be those from iteration 𝑘1 (even if some of the successor states had already been updated in iteration 𝑘). The difference is discussed in Sutton & Barto in Chapter 4.1 on page 91. CourseNana.COM

Note: A policy synthesized from values of depth 𝑘 (which reflect the next 𝑘 rewards) will actually reflect the next 𝑘+1 rewards (i.e. you return 𝜋𝑘+1). Similarly, the Q-values will also reflect one more reward than the values (i.e. you return 𝑄𝑘+1). CourseNana.COM

You should return the synthesized policy 𝜋𝑘+1. CourseNana.COM

Hint: You may optionally use the util.Counter class in util.py, which is a dictionary with a default value of zero. However, be careful with argMax: the actual argmax you want may be a key not in the counter! CourseNana.COM

Note: Make sure to handle the case when a state has no available actions in an MDP (think about what this means for future rewards). CourseNana.COM

To test your implementation, run the autograder: CourseNana.COM

python autograder.py -q q1

The following command loads your ValueIterationAgent, which will compute a policy and execute it 10 times. Press a key to cycle through values, Q-values, and the simulation. You should find that the value of the start state (V(start), which you can read off of the GUI) and the empirical resulting average reward (printed after the 10 rounds of execution finish) are quite close. CourseNana.COM

python gridworld.py -a value -i 100 -k 10

Hint: On the default BookGrid, running value iteration for 5 iterations should give you this output: CourseNana.COM

python gridworld.py -a value -i 5

Value iteration diagram CourseNana.COM

Grading: Your value iteration agent will be graded on a new grid. We will check your values, Q-values, and policies after fixed numbers of iterations and at convergence (e.g. after 100 iterations). CourseNana.COM


Question 2 (5 points): Policies

Consider the DiscountGrid layout, shown below. This grid has two terminal states with positive payoff (in the middle row), a close exit with payoff +1 and a distant exit with payoff +10. The bottom row of the grid consists of terminal states with negative payoff (shown in red); each state in this “cliff” region has payoff -10. The starting state is the yellow square. We distinguish between two types of paths: (1) paths that “risk the cliff” and travel near the bottom row of the grid; these paths are shorter but risk earning a large negative payoff, and are represented by the red arrow in the figure below. (2) paths that “avoid the cliff” and travel along the top edge of the grid. These paths are longer but are less likely to incur huge negative payoffs. These paths are represented by the green arrow in the figure below. CourseNana.COM

Paths in gridworld CourseNana.COM

In this question, you will choose settings of the discount, noise, and living reward parameters for this MDP to produce optimal policies of several different types. Your setting of the parameter values for each part should have the property that, if your agent followed its optimal policy without being subject to any noise, it would exhibit the given behavior. If a particular behavior is not achieved for any setting of the parameters, assert that the policy is impossible by returning the string 'NOT POSSIBLE'. CourseNana.COM

Here are the optimal policy types you should attempt to produce: CourseNana.COM

  1. Prefer the close exit (+1), risking the cliff (-10)
  2. Prefer the close exit (+1), but avoiding the cliff (-10)
  3. Prefer the distant exit (+10), risking the cliff (-10)
  4. Prefer the distant exit (+10), avoiding the cliff (-10)
  5. Avoid both exits and the cliff (so an episode should never terminate)

To see what behavior a set of numbers ends up in, run the following command to see a GUI: CourseNana.COM

python gridworld.py -g DiscountGrid -a value --discount [YOUR_DISCOUNT] --noise [YOUR_NOISE] --livingReward [YOUR_LIVING_REWARD]

To check your answers, run the autograder: CourseNana.COM

python autograder.py -q q2

question2a() through question2e() should each return a 3-item tuple of (discount, noise, living reward) in analysis.py. CourseNana.COM

Note: You can check your policies in the GUI. For example, using a correct answer to 3(a), the arrow in (0,1) should point east, the arrow in (1,1) should also point east, and the arrow in (2,1) should point north. CourseNana.COM

Note: On some machines you may not see an arrow. In this case, press a button on the keyboard to switch to qValue display, and mentally calculate the policy by taking the arg max of the available qValues for each state. CourseNana.COM

Grading: We will check that the desired policy is returned in each case. CourseNana.COM


Question 3 (5 points): Q-Learning

Note that your value iteration agent does not actually learn from experience. Rather, it ponders its MDP model to arrive at a complete policy before ever interacting with a real environment. When it does interact with the environment, it simply follows the precomputed policy (e.g. it becomes a reflex agent). This distinction may be subtle in a simulated environment like a Gridword, but it’s very important in the real world, where the real MDP is not available. CourseNana.COM

You will now write a Q-learning agent, which does very little on construction, but instead learns by trial and error from interactions with the environment through its update(state, action, nextState, reward) method. A stub of a Q-learner is specified in QLearningAgent in qlearningAgents.py, and you can select it with the option '-a q'. For this question, you must implement the updatecomputeValueFromQValuesgetQValue, and computeActionFromQValues methods. CourseNana.COM

Note: For computeActionFromQValues, you should break ties randomly for better behavior. The random.choice() function will help. In a particular state, actions that your agent hasn’t seen before still have a Q-value, specifically a Q-value of zero, and if all of the actions that your agent has seen before have a negative Q-value, an unseen action may be optimal. CourseNana.COM

Important: Make sure that in your computeValueFromQValues and computeActionFromQValues functions, you only access Q values by calling getQValue. This abstraction will be useful for question 10 when you override getQValue to use features of state-action pairs rather than state-action pairs directly. CourseNana.COM

With the Q-learning update in place, you can watch your Q-learner learn under manual control, using the keyboard: CourseNana.COM

python gridworld.py -a q -k 5 -m

Recall that -k will control the number of episodes your agent gets to learn. Watch how the agent learns about the state it was just in, not the one it moves to, and “leaves learning in its wake.” Hint: to help with debugging, you can turn off noise by using the --noise 0.0 parameter (though this obviously makes Q-learning less interesting). If you manually steer Pacman north and then east along the optimal path for four episodes, you should see the following Q-values: CourseNana.COM

Q-value diagram CourseNana.COM

Grading: We will run your Q-learning agent and check that it learns the same Q-values and policy as our reference implementation when each is presented with the same set of examples. To grade your implementation, run the autograder: CourseNana.COM

python autograder.py -q q3

Question 4 (2 points): Epsilon Greedy

Complete your Q-learning agent by implementing epsilon-greedy action selection in getAction, meaning it chooses random actions an epsilon fraction of the time, and follows its current best Q-values otherwise. Note that choosing a random action may result in choosing the best action - that is, you should not choose a random sub-optimal action, but rather any random legal action. CourseNana.COM

You can choose an element from a list uniformly at random by calling the random.choice function. You can simulate a binary variable with probability p of success by using util.flipCoin(p), which returns True with probability p and False with probability 1-p. CourseNana.COM

After implementing the getAction method, observe the following behavior of the agent in GridWorld (with epsilon = 0.3). CourseNana.COM

python gridworld.py -a q -k 100

Your final Q-values should resemble those of your value iteration agent, especially along well-traveled paths. However, your average returns will be lower than the Q-values predict because of the random actions and the initial learning phase. CourseNana.COM

You can also observe the following simulations for different epsilon values. Does that behavior of the agent match what you expect? CourseNana.COM

python gridworld.py -a q -k 100 --noise 0.0 -e 0.1
python gridworld.py -a q -k 100 --noise 0.0 -e 0.9

To test your implementation, run the autograder: CourseNana.COM

python autograder.py -q q4

With no additional code, you should now be able to run a Q-learning crawler robot: CourseNana.COM

python crawler.py

If this doesn’t work, you’ve probably written some code too specific to the GridWorld problem and you should make it more general to all MDPs. CourseNana.COM

This will invoke the crawling robot from class using your Q-learner. Play around with the various learning parameters to see how they affect the agent’s policies and actions. Note that the step delay is a parameter of the simulation, whereas the learning rate and epsilon are parameters of your learning algorithm, and the discount factor is a property of the environment. CourseNana.COM


Question 5 (1 point): Q-Learning and Pacman

Time to play some Pacman! Pacman will play games in two phases. In the first phase, training, Pacman will begin to learn about the values of positions and actions. Because it takes a very long time to learn accurate Q-values even for tiny grids, Pacman’s training games run in quiet mode by default, with no GUI (or console) display. Once Pacman’s training is complete, he will enter testing mode. When testing, Pacman’s self.epsilon and self.alpha will be set to 0.0, effectively stopping Q-learning and disabling exploration, in order to allow Pacman to exploit his learned policy. Test games are shown in the GUI by default. Without any code changes you should be able to run Q-learning Pacman for very tiny grids as follows: CourseNana.COM

python pacman.py -p PacmanQAgent -x 2000 -n 2010 -l smallGrid

Note that PacmanQAgent is already defined for you in terms of the QLearningAgent you’ve already written. PacmanQAgent is only different in that it has default learning parameters that are more effective for the Pacman problem (epsilon=0.05, alpha=0.2, gamma=0.8). You will receive full credit for this question if the command above works without exceptions and your agent wins at least 80% of the time. The autograder will run 100 test games after the 2000 training games. CourseNana.COM

Hint: If your QLearningAgent works for gridworld.py and crawler.py but does not seem to be learning a good policy for Pacman on smallGrid, it may be because your getAction and/or computeActionFromQValues methods do not in some cases properly consider unseen actions. In particular, because unseen actions have by definition a Q-value of zero, if all of the actions that have been seen have negative Q-values, an unseen action may be optimal. Beware of the argMax function from util.Counter! CourseNana.COM

To grade your answer, run: CourseNana.COM

python autograder.py -q q5

Note: If you want to experiment with learning parameters, you can use the option -a, for example -a epsilon=0.1,alpha=0.3,gamma=0.7. These values will then be accessible as self.epsilonself.gamma and self.alpha inside the agent. CourseNana.COM

Note: While a total of 2010 games will be played, the first 2000 games will not be displayed because of the option -x 2000, which designates the first 2000 games for training (no output). Thus, you will only see Pacman play the last 10 of these games. The number of training games is also passed to your agent as the option numTraining. CourseNana.COM

Note: If you want to watch 10 training games to see what’s going on, use the command: CourseNana.COM

python pacman.py -p PacmanQAgent -n 10 -l smallGrid -a numTraining=10

During training, you will see output every 100 games with statistics about how Pacman is faring. Epsilon is positive during training, so Pacman will play poorly even after having learned a good policy: this is because he occasionally makes a random exploratory move into a ghost. As a benchmark, it should take between 1000 and 1400 games before Pacman’s rewards for a 100 episode segment becomes positive, reflecting that he’s started winning more than losing. By the end of training, it should remain positive and be fairly high (between 100 and 350). CourseNana.COM

Pacman fails to win on larger layouts because each board configuration is a separate state with separate Q-values. He has no way to generalize that running into a ghost is bad for all positions. Obviously, this approach will not scale.
CourseNana.COM


Question 6 (3 points): Approximate Q-Learning

Implement an approximate Q-learning agent that learns weights for features of states, where many states might share the same features. Write your implementation in ApproximateQAgent class in qlearningAgents.py, which is a subclass of PacmanQAgent. CourseNana.COM

Note: Approximate Q-learning assumes the existence of a feature function 𝑓(𝑠,𝑎) over state and action pairs, which yields a vector [𝑓1(𝑠,𝑎),,𝑓𝑖(𝑠,𝑎),,𝑓𝑛(𝑠,𝑎)] of feature values. We provide feature functions for you in featureExtractors.py. Feature vectors are util.Counter (like a dictionary) objects containing the non-zero pairs of features and values; all omitted features have value zero. So, instead of an vector where the index in the vector defines which feature is which, we have the keys in the dictionary define the idenity of the feature. CourseNana.COM

The approximate Q-function takes the following form: CourseNana.COM

𝑄(𝑠,𝑎)=𝑖=1𝑛𝑓𝑖(𝑠,𝑎)𝑤𝑖 CourseNana.COM

where each weight 𝑤𝑖 is associated with a particular feature 𝑓𝑖(𝑠,𝑎). In your code, you should implement the weight vector as a dictionary mapping features (which the feature extractors will return) to weight values. You will update your weight vectors similarly to how you updated Q-values: CourseNana.COM

𝑤𝑖𝑤𝑖+𝛼difference𝑓𝑖(𝑠,𝑎)difference=(𝑟+𝛾max𝑎𝑄(𝑠,𝑎))𝑄(𝑠,𝑎) CourseNana.COM

Note that the difference term is the same as in normal Q-learning, and 𝑟 is the experienced reward. CourseNana.COM

By default, ApproximateQAgent uses the IdentityExtractor, which assigns a single feature to every (state,action) pair. With this feature extractor, your approximate Q-learning agent should work identically to PacmanQAgent. You can test this with the following command: CourseNana.COM

python pacman.py -p ApproximateQAgent -x 2000 -n 2010 -l smallGrid

ImportantApproximateQAgent is a subclass of QLearningAgent, and it therefore shares several methods like getAction. Make sure that your methods in QLearningAgent call getQValue instead of accessing Q-values directly, so that when you override getQValue in your approximate agent, the new approximate q-values are used to compute actions. CourseNana.COM

Submission CourseNana.COM

In order to submit your project upload the Python files you edited. For instance, use Gradescope’s upload on all .py files in the project folder. CourseNana.COM

Get in Touch with Our Experts

WeChat (微信) WeChat (微信)
Whatsapp WhatsApp
Berkeley代写,CS188代写,Introduction to Artificial Intelligence代写,Reinforcement Learning代写,Python代写,Value Iteration代写,Q-Learning代写,Epsilon Greedy代写,Berkeley代编,CS188代编,Introduction to Artificial Intelligence代编,Reinforcement Learning代编,Python代编,Value Iteration代编,Q-Learning代编,Epsilon Greedy代编,Berkeley代考,CS188代考,Introduction to Artificial Intelligence代考,Reinforcement Learning代考,Python代考,Value Iteration代考,Q-Learning代考,Epsilon Greedy代考,Berkeleyhelp,CS188help,Introduction to Artificial Intelligencehelp,Reinforcement Learninghelp,Pythonhelp,Value Iterationhelp,Q-Learninghelp,Epsilon Greedyhelp,Berkeley作业代写,CS188作业代写,Introduction to Artificial Intelligence作业代写,Reinforcement Learning作业代写,Python作业代写,Value Iteration作业代写,Q-Learning作业代写,Epsilon Greedy作业代写,Berkeley编程代写,CS188编程代写,Introduction to Artificial Intelligence编程代写,Reinforcement Learning编程代写,Python编程代写,Value Iteration编程代写,Q-Learning编程代写,Epsilon Greedy编程代写,Berkeleyprogramming help,CS188programming help,Introduction to Artificial Intelligenceprogramming help,Reinforcement Learningprogramming help,Pythonprogramming help,Value Iterationprogramming help,Q-Learningprogramming help,Epsilon Greedyprogramming help,Berkeleyassignment help,CS188assignment help,Introduction to Artificial Intelligenceassignment help,Reinforcement Learningassignment help,Pythonassignment help,Value Iterationassignment help,Q-Learningassignment help,Epsilon Greedyassignment help,Berkeleysolution,CS188solution,Introduction to Artificial Intelligencesolution,Reinforcement Learningsolution,Pythonsolution,Value Iterationsolution,Q-Learningsolution,Epsilon Greedysolution,