了解 Q-Learning 的一個好方法,就是將 Catch 游戲和下象棋進行比較。
?
在這兩種游戲中,你都會得到一個狀態 S。在象棋中,這代表棋盤上棋子的位置。在 Catch 游戲中,這代表水果和籃子的位置。
?
然后,玩家要采取一個動作,稱作 A。在象棋中,玩家要移動一個棋子。而在 Catch 游戲中,這代表著將籃子向左、向右移動,或是保持在當前位置。據此,會得到一些獎勵 R 和一個新狀態 S'。
Catch 游戲和象棋的一個共同點在于,獎勵并不會立即出現在動作之后。
?
在 Catch 游戲中,只有在水果掉到籃子里或是撞到地板上時你才會獲得獎勵。而在象棋中,只有在整盤棋贏了或輸了之后,才會獲得獎勵。這也就是說,獎勵是稀疏分布的(sparsely distributed)。大多數時候,R 保持為零。
?
產生的獎勵并不總是前一個動作的結果。也許,很早之前采取的某些動作才是獲勝的關鍵。要弄清楚哪個動作對最終的獎勵負責,這通常被稱為信度分配問題(credit assignment problem)。
?
由于獎勵的延遲性,優秀的象棋選手并不會僅通過最直接可見的獎勵來選擇他們的落子方式。相反,他們會考慮預期未來獎勵(expected future reward),并據此進行選擇。例如,他們不僅要考慮下一步是否能夠消滅對手的一個棋子。他們也會考慮那些從長遠的角度有益的行為。
?
在 Q-Learning 中,我們根據最高的預期未來獎勵選行動。我們使用 Q 函數進行計算。這個數學函數有兩個變量:游戲的當前狀態和給定的動作。因此,我們可以將其記為 Q(state,action)。在 S 狀態下,我們將估計每個可能的動作 A 所帶來的的回報。我們假定在采取行動 A 且進入下一個狀態 S' 以后,一切都很完美。
?
對于給定狀態 S 和動作 A,預期未來獎勵 Q(S,A)被計算為即時獎勵 R 加上其后的預期未來獎勵 Q(S',A')。我們假設下一個動作 A' 是最優的。
?
由于未來的不確定性,我們用 γ 因子乘以 Q(S',A')表示折扣:
Q(S,A) = R + γ * max Q(S',A')
?
象棋高手擅長在心里估算未來回報。換句話說,他們的 Q 函數 Q(S,A)非常精確。大多數象棋訓練都是圍繞著發展更好的 Q 函數進行的。玩家使用棋譜學習,從而了解特定動作如何發生,以及給定的動作有多大可能會導致勝利。但是,機器如何評估一個 Q 函數的好壞呢?這就是神經網絡大展身手的地方了。
?
最終回歸
?
玩游戲的時候,我們會產生很多「經歷」,包括以下幾個部分:
初始狀態,S
采取的動作,A
獲得的獎勵,R
下一狀態,S'
這些經歷就是我們的訓練數據。我們可以將估算 Q(S,A)的問題定義為回歸問題。為了解決這個問題,我們可以使用神經網絡。給定一個由 S 和 A 組成的輸入向量,神經網絡需要能預測 Q(S,A)的值等于目標:R + γ * max Q(S',A')。
?
如果我們能很好地預測不同狀態 S 和不同行為 A 的 Q(S,A),我們就能很好地逼近 Q 函數。請注意,我們通過與 Q(S,A)相同的神經網絡估算 Q(S',A')。
?
訓練過程
?
給定一批經歷 ,其訓練過程如下:
?
1、對于每個可能的動作 A'(向左、向右、不動),使用神經網絡預測預期未來獎勵 Q(S',A');
2、選擇 3 個預期未來獎勵中的最大值,作為 max Q(S',A');
3、計算 r + γ * max Q(S',A'),這就是神經網絡的目標值;
4、使用損失函數(loss function)訓練神經網絡。損失函數可以計算預測值離目標值的距離。此處,我們使用 0.5 * (predicted_Q(S,A)—target)2 作為損失函數。
?
在游戲過程中,所有的經歷都會被存儲在回放存儲器(replay memory)中。這就像一個存儲 對的簡單緩存。這些經歷回放類同樣能用于準備訓練數據。讓我們看看下面的代碼:
classExperienceReplay(object):""" During gameplay all the experiences < s, a, r, s’ > are stored in a replay memory. In training, batches of randomly drawn experiences are used to generate the input and target for training. """def__init__(self, max_memory=100, discount=.9):""" Setup max_memory: the maximum number of experiences we want to store memory: a list of experiences discount: the discount factor for future experience In the memory the information whether the game ended at the state is stored seperately in a nested array [... [experience, game_over] [experience, game_over] ...] """self.max_memory = max_memory self.memory = list() self.discount = discountdefremember(self, states, game_over):#Save a state to memoryself.memory.append([states, game_over])#We don't want to store infinite memories, so if we have too many, we just delete the oldest oneiflen(self.memory) > self.max_memory:delself.memory[0]defget_batch(self, model, batch_size=10):#How many experiences do we have?len_memory = len(self.memory)#Calculate the number of actions that can possibly be taken in the gamenum_actions = model.output_shape[-1]#Dimensions of the game fieldenv_dim = self.memory[0][0][0].shape[1]#We want to return an input and target vector with inputs from an observed state...inputs = np.zeros((min(len_memory, batch_size), env_dim))#...and the target r + gamma * max Q(s’,a’)#Note that our target is a matrix, with possible fields not only for the action taken but also#for the other possible actions. The actions not take the same value as the prediction to not affect themtargets = np.zeros((inputs.shape[0], num_actions))#We draw states to learn from randomlyfori, idxinenumerate(np.random.randint(0, len_memory, size=inputs.shape[0])):""" Here we load one transition from memory state_t: initial state s action_t: action taken a reward_t: reward earned r state_tp1: the state that followed s’ """state_t, action_t, reward_t, state_tp1 = self.memory[idx][0]#We also need to know whether the game ended at this stategame_over = self.memory[idx][1]#add the state s to the inputinputs[i:i+1] = state_t# First we fill the target values with the predictions of the model.# They will not be affected by training (since the training loss for them is 0)targets[i] = model.predict(state_t)[0]""" If the game ended, the expected reward Q(s,a) should be the final reward r. Otherwise the target value is r + gamma * max Q(s’,a’) """# Here Q_sa is max_a'Q(s', a')Q_sa = np.max(model.predict(state_tp1)[0])#if the game ended, the reward is the final rewardifgame_over:# if game_over is Truetargets[i, action_t] = reward_telse:# r + gamma * max Q(s’,a’)targets[i, action_t] = reward_t + self.discount * Q_sareturninputs, targets
?
定義模型
?
評論