Tuesday, October 9, 2018

The Problem:

The problem is about finding a path to the Princess ignoring the enemies. In the below figure "K" represents "Knights", "P" represents "Princess", and "E" represents "Enemy". In the figure, blank cell means, the knight can move to that cell. e.g, the knight can move to right and down only. Knight will be killed if moves to the enemy cell.

Solution:

*You can download the entire Python code here.

We will solve this using Q-learn algorithm and implement using Python. We will not use any other library such as gym
To implement from the scratch, we need to understand the Q-learn algorithm and the problem itself. It is recommended, to go through the theory of Q-learn reinforcement algorithm.

Step-1: Represent the problem mathematically.
As we know, the Q-learn algorithm is all about states and actions. So in our problem, let the current position of the Knight is the "state". So lets numbered the all possible position as states number (starting from state #0), in below figure.

So, the state of knight is 0. The state of Princess is 22. The states of enemies are 6, 8, 12, 15, and 19. The objective is to move the knight from state 0 to state 22 ignoring states 6, 8, 12, 15, and 19.
The possible actions from each state can be UP (action 0), DOWN (action 1), LEFT (action 2), and RIGHT (action 3). For each movement, the knight will be rewarded.

Step-2: Create the reward matrix

 1 2 import numpy as np R = np.full((25,4),-1)

For each legal movement the knight will be rewarded -1 (which is default).
However if the next state is the states of enemies, then the reward value will be -100.

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 # reward to reach knight at state 6 is -100 R = -100.0 R = -100.0 R = -100.0 R = -100.0 # reward to reach knight at state 8 is -100 R = -100.0 R = -100.0 R = -100.0 R = -100.0 # reward to reach knight at state 12 is -100 R = -100.0 R = -100.0 R = -100.0 R = -100.0 # reward to reach knight at state 15 is -100 R = -100.0 R = -100.0 R = -100.0 # reward to reach knight at state 19 is -100 R = -100.0 R = -100.0 R = -100.0

And if the next state is 22 (i.e. state of Princess) than the reward value will be 100.

 1 2 3 4 # reward to reach the castle (prince) at state 22 is 100 R = 100.0 R = 100.0 R = 100.0

To define the illegal movement by using -2 as reward value. For example, the knight can not move UP from state 0.

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 # -2 represent the illegal movement illegal = -2 # illegal movement from states in FIRST ROW R=illegal R= illegal R= illegal R= illegal R= illegal # illegal movement from states in FIRST COLUMN R= illegal R= illegal R= illegal R= illegal R= illegal # illegal movement from states in LAST ROW R= illegal R= illegal R= illegal R= illegal R= illegal # illegal movement from states in LAST COLUMN R= illegal R= illegal R= illegal R= illegal R= illegal

Step-2: Create the Q matrix

 1 2 3 4 5 noOfState = 25 noOfAction = 4 # Q matrix Q = np.zeros((noOfState,noOfAction))
Set the learning rate (alpha) to 0.8 and the discount rate (gamma) to 0.2.

 1 2 gamma = 0.2 alpha = 0.8
Step-3: Create the supporting functions
Function to return all possible action that can be taken from any state
 1 2 3 4 def available_directions_to_go(state): curr_state_row = R[state,] act = np.where(curr_state_row != -2) return act

Function to select and return one action from all possible actions
 1 2 3 def next_action_dir(all_psbl_directions): next_action_dir = int(np.random.choice(all_psbl_directions)) return next_action_dir

Function to return the next state value after applying any specific action

 1 2 3 4 5 6 7 8 9 10 11 12 def next_state(current_state, direction): if direction == 0: # UP direction st= current_state-5 if direction == 1: # DOWN direction st = current_state+5 if direction == 2: # LEFT direction st = current_state-1 if direction == 3: # RIGHT direction st = current_state+1 if verify_state(st) == False: print("6. Something wrong: (current_state, direction) ", current_state, direction) return st

Function to update the Q matrix

 1 2 3 4 5 6 7 8 9 10 11 def updateQ(cur_state,action_dir,gamma): if verify_state(cur_state) == False or verify_action(action_dir)==False: print("3. something is Wrong") next_st = next_state(cur_state, action_dir) if verify_state(next_st) == False: print("4. something is Wrong: (next_st, cur_state, action_dir)",next_st, cur_state, action_dir) print(Q) index_of_max_val = np.where(R[next_st,] == np.max(R[next_st,])) if verify_action(index_of_max_val)==False: print("5. something is Wrong") Q[cur_state, action_dir] = Q[cur_state, action_dir] + alpha*(R[cur_state, action_dir]+ gamma*(Q[next_st,index_of_max_val] - Q[cur_state, action_dir]))

Step- 4: Training
Now its time to train the Q matrix.

 1 2 3 4 5 6 7 8 9 10 for i in range(50000): cur_state = np.random.randint(0,noOfState) if verify_state(cur_state) == False: print("1. something is Wrong") next_act_dir = next_action_dir(available_directions_to_go(cur_state)) if verify_action(next_act_dir) == False: print("2. something is Wrong") updateQ(cur_state, next_act_dir, gamma) if i%10000 == 0: print("10k iterations finished.")

Step-5: Testing
After training the Q-matrix, the resultant matrix can be use to fin the path from state 0 to state 22.

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 print("After training below is the Q matrix: ") for i in range(Q.shape): print(i," ",Q[i,]) start_st = 0 goal_st = 22 path = [start_st] while start_st != goal_st: tmp = Q[start_st,] row_max = np.max(tmp[tmp != 0]) max_reward_act_dir = np.where(Q[start_st,]==row_max) next_st = next_state(start_st, max_reward_act_dir) path.append(next_st) start_st = next_st print("Path from state ",start_st," to state ",goal_st,": ",path)

The procedure to find the path is as follows:
5.a.  Start from the state of knight. In our case it is state 0
5.b.  Find the maximum value but should not be 0. The cell value 0 represents the illegal movement. So we should ignore such movement.
5.c.  Find the corresponding action direction. For example, if the maximum value is present at index 2. This mean, the knight should move towards LEFT direction.
5.d.  Go the next state and make that state as current state
5.e.  If the current state is not goal state or the state of Princess, repeat from Step-5.b
5.f.  If the current state is goal state, print the sequence of states knight has visited.

Change the value of start_st and goal_st to change the  position of Knight and Princess, respectively. Play around the value of gamma and alpha to train the Q matrix.
You can download the entire Python code here.

Thats all for now.

-Thanks
{"ft_lang_label":"__label__en","ft_lang_prob":0.8129053,"math_prob":0.99200886,"size":7472,"snap":"2019-43-2019-47","text_gpt3_token_len":2232,"char_repetition_ratio":0.16242635,"word_repetition_ratio":0.2189781,"special_character_ratio":0.3440846,"punctuation_ratio":0.13312303,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9875637,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-10-20T06:17:25Z\",\"WARC-Record-ID\":\"<urn:uuid:e5b625cc-4215-4a1e-bb0f-e1c746bcf656>\",\"Content-Length\":\"112853\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:4bb734d3-f05e-4fcc-bc06-eccb95ae3df6>\",\"WARC-Concurrent-To\":\"<urn:uuid:d9cadfad-b576-40a7-b8da-99ccbe327402>\",\"WARC-IP-Address\":\"172.217.7.161\",\"WARC-Target-URI\":\"https://blogchinmaya.blogspot.com/2018/10/q-learn-solving-knight-and-princess.html\",\"WARC-Payload-Digest\":\"sha1:6AFVLNZBLA4YAKZM6P2R36B7SFOV5XJ2\",\"WARC-Block-Digest\":\"sha1:JUBEUT4NN6Z25GKXIVED7G57A6DRD2JR\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-43/CC-MAIN-2019-43_segments_1570986703625.46_warc_CC-MAIN-20191020053545-20191020081045-00376.warc.gz\"}"}