# Train Reinforcement Learning Agent in Basic Grid World

This example shows how to solve a grid world environment using reinforcement learning by training Q-learning and SARSA agents. For more information on these agents, see Q-Learning Agents and SARSA Agents.

This grid world environment has the following configuration and rules:

1. The grid world is 5-by-5 and bounded by borders, with four possible actions (North = 1, South = 2, East = 3, West = 4).

2. The agent begins from cell [2,1] (second row, first column).

3. The agent receives a reward +10 if it reaches the terminal state at cell [5,5] (blue).

4. The environment contains a special jump from cell [2,4] to cell [4,4] with a reward of +5.

5. The agent is blocked by obstacles (black cells).

6. All other actions result in –1 reward. ### Create Grid World Environment

Create the basic grid world environment.

`env = rlPredefinedEnv("BasicGridWorld");`

To specify that the initial state of the agent is always [2,1], create a reset function that returns the state number for the initial agent state. This function is called at the start of each training episode and simulation. States are numbered starting at position [1,1]. The state number increases as you move down the first column and then down each subsequent column. Therefore, create an anonymous function handle that sets the initial state to `2`.

`env.ResetFcn = @() 2;`

Fix the random generator seed for reproducibility.

`rng(0)`

### Create Q-Learning Agent

To create a Q-learning agent, first create a Q table using the observation and action specifications from the grid world environment. Set the learning rate of the representation to 1.

```qTable = rlTable(getObservationInfo(env),getActionInfo(env)); qRepresentation = rlQValueRepresentation(qTable,getObservationInfo(env),getActionInfo(env)); qRepresentation.Options.LearnRate = 1;```

Next, create a Q-learning agent using this table representation and configure the epsilon-greedy exploration. For more information on creating Q-learning agents, see `rlQAgent` and `rlQAgentOptions`.

```agentOpts = rlQAgentOptions; agentOpts.EpsilonGreedyExploration.Epsilon = .04; qAgent = rlQAgent(qRepresentation,agentOpts);```

### Train Q-Learning Agent

To train the agent, first specify the training options. For this example, use the following options:

• Train for at most 200 episodes. Specify that each episode lasts for most 50 time steps.

• Stop training when the agent receives an average cumulative reward greater than 10 over 30 consecutive episodes.

For more information, see `rlTrainingOptions`.

```trainOpts = rlTrainingOptions; trainOpts.MaxStepsPerEpisode = 50; trainOpts.MaxEpisodes= 200; trainOpts.StopTrainingCriteria = "AverageReward"; trainOpts.StopTrainingValue = 11; trainOpts.ScoreAveragingWindowLength = 30;```

Train the Q-learning agent using the `train` function. Training can take several minutes to complete. To save time while running this example, load a pretrained agent by setting `doTraining` to `false`. To train the agent yourself, set `doTraining` to `true`.

```doTraining = false; if doTraining % Train the agent. trainingStats = train(qAgent,env,trainOpts); else % Load the pretrained agent for the example. load('basicGWQAgent.mat','qAgent') end```

The Episode Manager window opens and displays the training progress. ### Validate Q-Learning Results

To validate the training results, simulate the agent in the training environment.

Before running the simulation, visualize the environment and configure the visualization to maintain a trace of the agent states.

```plot(env) env.Model.Viewer.ShowTrace = true; env.Model.Viewer.clearTrace;```

Simulate the agent in the environment using the `sim` function.

`sim(qAgent,env)` The agent trace shows that the agent successfully finds the jump from cell [2,4] to cell [4,4].

### Create and Train SARSA Agent

To create a SARSA agent, use the same Q table representation and epsilon-greedy configuration as for the Q-learning agent. For more information on creating SARSA agents, see `rlSARSAAgent` and `rlSARSAAgentOptions`.

```agentOpts = rlSARSAAgentOptions; agentOpts.EpsilonGreedyExploration.Epsilon = 0.04; sarsaAgent = rlSARSAAgent(qRepresentation,agentOpts);```

Train the SARSA agent using the `train` function. Training can take several minutes to complete. To save time while running this example, load a pretrained agent by setting `doTraining` to `false`. To train the agent yourself, set `doTraining` to `true`.

```doTraining = false; if doTraining % Train the agent. trainingStats = train(sarsaAgent,env,trainOpts); else % Load the pretrained agent for the example. load('basicGWSarsaAgent.mat','sarsaAgent') end``` ### Validate SARSA Training

To validate the training results, simulate the agent in the training environment.

```plot(env) env.Model.Viewer.ShowTrace = true; env.Model.Viewer.clearTrace;```

Simulate the agent in the environment.

`sim(sarsaAgent,env)` The SARSA agent finds the same grid world solution as the Q-learning agent.
{"ft_lang_label":"__label__en","ft_lang_prob":0.7384617,"math_prob":0.8242478,"size":4663,"snap":"2020-34-2020-40","text_gpt3_token_len":1067,"char_repetition_ratio":0.15668598,"word_repetition_ratio":0.21085271,"special_character_ratio":0.20759168,"punctuation_ratio":0.17406963,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9612192,"pos_list":[0,1,2,3,4,5,6,7,8,9,10,11,12],"im_url_duplicate_count":[null,1,null,1,null,1,null,1,null,1,null,1,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-09-30T22:10:49Z\",\"WARC-Record-ID\":\"<urn:uuid:2d034086-d8b4-47b5-9e7e-5b6b6c8f87e0>\",\"Content-Length\":\"80211\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:ded8d2c8-c2eb-4ba3-bfaa-ae642be10a92>\",\"WARC-Concurrent-To\":\"<urn:uuid:33b59827-e2c7-4400-85f2-bbb3e7ee35ba>\",\"WARC-IP-Address\":\"104.119.17.62\",\"WARC-Target-URI\":\"https://ww2.mathworks.cn/help/reinforcement-learning/ug/train-q-learning-agent-to-solve-basic-grid-world.html\",\"WARC-Payload-Digest\":\"sha1:4KFATJ4RNGY7KSKBKO5FOYILCECONJNA\",\"WARC-Block-Digest\":\"sha1:DDSQABSZ7TCLGI6YI76ESWG6NWCMVQUO\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-40/CC-MAIN-2020-40_segments_1600402128649.98_warc_CC-MAIN-20200930204041-20200930234041-00531.warc.gz\"}"}