深度強化學習
1 強化學習是一種什么樣的方法
強化學習作為一個序列決策(Sequential Decision Making)問題,它需要連續選擇一些行為,從這些行為完成后得到最大的收益作為最好的結果。它在沒有任何label告訴算法應該怎么做的情況下,通過先嘗試做出一些行為——然后得到一個結果,通過判斷這個結果是對還是錯來對之前的行為進行反饋。由這個反饋來調整之前的行為,通過不斷的調整算法能夠學習到在什么樣的情況下選擇什么樣的行為可以得到最好的結果。
2 通俗語言解釋
我們訓練出一個人工大腦Agent,這個Agent可以對環境Environment中的狀態Status做出判斷,讀取環境的狀態,并做出行動Action.
這個人工大腦做出行動之后,環境會根據受到的來自Agent的行動給這個Agent進行反饋Reward,這個人工大腦會根具環境的反饋做出改進,從而做出更好Improve的行動.
就是這樣一個循環往復的過程,Agent不斷地嘗試,不斷地改進自己。
那么如何讓Agent變得足夠遠見,能夠從長遠的角度優化當前固定行動,而不是急功近利呢。所以Agent 每一步都要需要向著獲得最大利益那邊靠齊。
3 具體案例 Flappy Bird with DQ
這里寫圖片描述
在這個案例里面就要實現一個人工大腦。
這個Agent可以讀取游戲的畫面,然后判斷是點擊屏幕還是不動以控制小鳥飛躍障礙物。
經過長時間的訓練,得到的Agent幾乎可以一直玩下去。
訓練一個小時之后
訓練了一個小時之后
可以看到剛開始的時候還不是很流暢。
對于這樣一個游戲來說。
Agent 即我們用來讀取圖像信息并做出分析的CNN網絡
Environment 即這個已經封裝起來的游戲,輸入Action,并反饋回來Reward和Status(S_t+1)(還有是否游戲結束狀態即terminal,這個 也可以視為Reward)
Action 即對屏幕的點擊操作,選擇點擊或者不點擊
Reward 即環境對Action的反饋
Status 即環境目前的狀態 S_t
以上就是一個深度強化網絡所需的五大要素,我們整個代碼實現都是圍繞這五個要素來進行邏輯實現。
代碼邏輯結構
整個代碼邏輯相對來說比較復雜,且聽我娓娓道來。
1 我們從對游戲圖像的分析開始,在無輸入的時候,初始化游戲圖像數據,進行基本處理,將圖像轉化為80 804 的矩陣Status即s_t,以這個數據矩陣作為神經網絡的輸入。
? ? # 初始化
? ? # 將圖像轉化為80*80*4 的矩陣
? ? do_nothing = np.zeros(ACTIONS)
? ? do_nothing[0] = 1
? ? x_t, r_0, terminal = game_state.frame_step(do_nothing)
? ? # 將圖像轉換成80*80,并進行灰度化
? ? x_t = cv2.cvtColor(cv2.resize(x_t, (80, 80)), cv2.COLOR_BGR2GRAY)
? ? # 對圖像進行二值化
? ? ret, x_t = cv2.threshold(x_t, 1, 255, cv2.THRESH_BINARY)
? ? # 將圖像處理成4通道
? ? s_t = np.stack((x_t, x_t, x_t, x_t), axis=2)
第一階段循環開始
2 將Status即s_t輸入到Agent即CNN網絡中得到分析結構(二分類),并由分析結果readout _t通過得到Action即a _t
? ? ? ? # 將當前環境輸入到CNN網絡中
? ? ? ? readout_t = readout.eval(feed_dict={s: [s_t]})[0]
? ? ? ? a_t = np.zeros([ACTIONS])
? ? ? ? action_index = 0
? ? ? ? if t % FRAME_PER_ACTION == 0:
? ? ? ? ? ? if random.random() <= epsilon:
? ? ? ? ? ? ? ? print("----------Random Action----------")
? ? ? ? ? ? ? ? action_index = random.randrange(ACTIONS)
? ? ? ? ? ? ? ? a_t[random.randrange(ACTIONS)] = 1
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? action_index = np.argmax(readout_t)
? ? ? ? ? ? ? ? a_t[action_index] = 1
? ? ? ? else:
? ? ? ? ? ? a_t[0] = 1? # do nothing
3 將Action即a _t輸入到Environment即game _state游戲中,得到Reward即r _t和s _t1和terminal
? ? ? ? # 其次,執行選擇的動作,并保存返回的狀態、得分。
? ? ? ? x_t1_colored, r_t, terminal = game_state.frame_step(a_t)
? ? ? ? x_t1 = cv2.cvtColor(cv2.resize(x_t1_colored, (80, 80)), cv2.COLOR_BGR2GRAY)
? ? ? ? ret, x_t1 = cv2.threshold(x_t1, 1, 255, cv2.THRESH_BINARY)
? ? ? ? x_t1 = np.reshape(x_t1, (80, 80, 1))
? ? ? ? s_t1 = np.append(x_t1, s_t[:, :, :3], axis=2)
4 將這些經驗數據進行保存
D.append((s_t, a_t, r_t, s_t1, terminal))
這是前10000次的循環,在通過分析結果readout
_t得到Action的過程中,加入隨機因素,使得Agent有一定的概率進行隨機選擇Action. 而且前面的循環是沒有強化過程的步驟的,就是要積累數據
? ? # 縮小 epsilon
? ? if epsilon > FINAL_EPSILON and t > OBSERVE:
? ? ? ? epsilon -= (INITIAL_EPSILON - FINAL_EPSILON) / EXPLORE
后面的循環,隨著循環的進步,不斷Agent隨機選擇Action的概率。 開始循環開始才有強化過程
第二階段循環開始
2 將Status即s_t輸入到Agent即CNN網絡中得到分析結構(二分類),并由分析結果readout _t通過得到Action即a _t
3 將Action即a _t輸入到Environment即game _state游戲中,得到Reward即r _t和s _t1和terminal
4 將這些經驗數據進行保存D.append((s_t, a_t, r_t, s_t1, terminal))
5 從D中抽取一定數量BATCH的經驗數據
minibatch = random.sample(D, BATCH)
# 從經驗池D中隨機提取馬爾科夫序列
s_j_batch = [d[0] for d in minibatch]
a_batch = [d[1] for d in minibatch]
r_batch = [d[2] for d in minibatch]
s_j1_batch = [d[3] for d in minibatch]
6 此處是關鍵所在,y_batch表示標簽值,如果下一時刻游戲關閉則直接用獎勵做標簽值,若游戲沒有關閉,則要在獎勵的基礎上加上GAMMA比例的下一時刻最大的模型預測值
y_batch = []
? ? ? ? ? ? readout_j1_batch = readout.eval(feed_dict={s: s_j1_batch})
? ? ? ? ? ? for i in range(0, len(minibatch)):
? ? ? ? ? ? ? ? terminal = minibatch[i][4]
? ? ? ? ? ? ? ? # if terminal, only equals reward
? ? ? ? ? ? ? ? if terminal:
? ? ? ? ? ? ? ? ? ? y_batch.append(r_batch[i])
? ? ? ? ? ? ? ? else:
? ? ? ? ? ? ? ? ? ? y_batch.append(r_batch[i] + GAMMA * np.max(readout_j1_batch[i]))
7 強化學習過程,此處采用了梯度下降對整個預測值進行收斂,通過對標簽值與當前模型預估行動的差值進行分析
? ? a = tf.placeholder("float", [None, ACTIONS])
? ? y = tf.placeholder("float", [None])
? ? readout_action = tf.reduce_sum(tf.multiply(readout, a), reduction_indices=1)
? ? cost = tf.reduce_mean(tf.square(y - readout_action))
? ? train_step = tf.train.AdamOptimizer(1e-6).minimize(cost)
? ? # perform gradient step
? ? train_step.run(feed_dict={
? ? ? ? y: y_batch,
? ? ? ? a: a_batch,
? ? ? ? s: s_j_batch}
? ? )
綜上 ,這個模型的主要框架即是如此。
源代碼如下
#!/usr/bin/env python
from __future__ import print_function
import tensorflow as tf
import cv2
import sys
sys.path.append("game/")
import wrapped_flappy_bird as game
import random
import numpy as np
from collections import deque
GAME = 'bird'? # the name of the game being played for log files
ACTIONS = 2? # number of valid actions
GAMMA = 0.99? # decay rate of past observations
OBSERVE = 10000.? # timesteps to observe before training
EXPLORE = 2000000.? # frames over which to anneal epsilon
FINAL_EPSILON = 0.0001? # final value of epsilon
INITIAL_EPSILON = 0.0001? # starting value of epsilon
REPLAY_MEMORY = 50000? # number of previous transitions to remember
BATCH = 32? # size of minibatch
FRAME_PER_ACTION = 1
# CNN 模型
# 權重
def weight_variable(shape):
? ? initial = tf.truncated_normal(shape, stddev=0.01)
? ? return tf.Variable(initial)
# 偏置
def bias_variable(shape):
? ? initial = tf.constant(0.01, shape=shape)
? ? return tf.Variable(initial)
# 卷積函數
def conv2d(x, W, stride):
? ? return tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding="SAME")
# 池化 核 2*2 步長2
def max_pool_2x2(x):
? ? return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
# 創建網絡
def createNetwork():
? ? # network weights
? ? W_conv1 = weight_variable([8, 8, 4, 32])
? ? b_conv1 = bias_variable([32])
? ? W_conv2 = weight_variable([4, 4, 32, 64])
? ? b_conv2 = bias_variable([64])
? ? W_conv3 = weight_variable([3, 3, 64, 64])
? ? b_conv3 = bias_variable([64])
? ? W_fc1 = weight_variable([1600, 512])
? ? b_fc1 = bias_variable([512])
? ? W_fc2 = weight_variable([512, ACTIONS])
? ? b_fc2 = bias_variable([ACTIONS])
? ? # 輸入層 輸入向量為80*80*4
? ? # input layer
? ? s = tf.placeholder("float", [None, 80, 80, 4])
? ? # hidden layers
? ? # 第一個隱藏層+一個池化層
? ? h_conv1 = tf.nn.relu(conv2d(s, W_conv1, 4) + b_conv1)
? ? h_pool1 = max_pool_2x2(h_conv1)
? ? # 第二個隱藏層
? ? h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2, 2) + b_conv2)
? ? # h_pool2 = max_pool_2x2(h_conv2)
? ? # 第三個隱藏層
? ? h_conv3 = tf.nn.relu(conv2d(h_conv2, W_conv3, 1) + b_conv3)
? ? # h_pool3 = max_pool_2x2(h_conv3)
? ? # 展平
? ? # h_pool3_flat = tf.reshape(h_pool3, [-1, 256])
? ? h_conv3_flat = tf.reshape(h_conv3, [-1, 1600])
? ? # 第一個全連接層
? ? h_fc1 = tf.nn.relu(tf.matmul(h_conv3_flat, W_fc1) + b_fc1)
? ? # 輸出層
? ? # readout layer
? ? readout = tf.matmul(h_fc1, W_fc2) + b_fc2
? ? return s, readout, h_fc1
def trainNetwork(s, readout, h_fc1, sess):
? ? # 定義損失函數
? ? # define the cost function
? ? a = tf.placeholder("float", [None, ACTIONS])
? ? y = tf.placeholder("float", [None])
? ? readout_action = tf.reduce_sum(tf.multiply(readout, a), reduction_indices=1)
? ? cost = tf.reduce_mean(tf.square(y - readout_action))
? ? train_step = tf.train.AdamOptimizer(1e-6).minimize(cost)
? ? # open up a game state to communicate with emulator
? ? game_state = game.GameState()
? ? # store the previous observations in replay memory
? ? D = deque()
? ? # printing
? ? a_file = open("logs_" + GAME + "/readout.txt", 'w')
? ? h_file = open("logs_" + GAME + "/hidden.txt", 'w')
? ? # 初始化
? ? # 將圖像轉化為80*80*4 的矩陣
? ? do_nothing = np.zeros(ACTIONS)
? ? do_nothing[0] = 1
? ? x_t, r_0, terminal = game_state.frame_step(do_nothing)
? ? # 將圖像轉換成80*80,并進行灰度化
? ? x_t = cv2.cvtColor(cv2.resize(x_t, (80, 80)), cv2.COLOR_BGR2GRAY)
? ? # 對圖像進行二值化
? ? ret, x_t = cv2.threshold(x_t, 1, 255, cv2.THRESH_BINARY)
? ? # 將圖像處理成4通道
? ? s_t = np.stack((x_t, x_t, x_t, x_t), axis=2)
? ? # 保存和載入網絡
? ? saver = tf.train.Saver()
? ? sess.run(tf.initialize_all_variables())
? ? checkpoint = tf.train.get_checkpoint_state("saved_networks")
? ? if checkpoint and checkpoint.model_checkpoint_path:
? ? ? ? saver.restore(sess, checkpoint.model_checkpoint_path)
? ? ? ? print("Successfully loaded:", checkpoint.model_checkpoint_path)
? ? else:
? ? ? ? print("Could not find old network weights")
? ? # 開始訓練
? ? epsilon = INITIAL_EPSILON
? ? t = 0
? ? while "flappy bird" != "angry bird":
? ? ? ? # choose an action epsilon greedily
? ? ? ? # 將當前環境輸入到CNN網絡中
? ? ? ? readout_t = readout.eval(feed_dict={s: [s_t]})[0]
? ? ? ? a_t = np.zeros([ACTIONS])
? ? ? ? action_index = 0
? ? ? ? if t % FRAME_PER_ACTION == 0:
? ? ? ? ? ? if random.random() <= epsilon:
? ? ? ? ? ? ? ? print("----------Random Action----------")
? ? ? ? ? ? ? ? action_index = random.randrange(ACTIONS)
? ? ? ? ? ? ? ? a_t[random.randrange(ACTIONS)] = 1
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? action_index = np.argmax(readout_t)
? ? ? ? ? ? ? ? a_t[action_index] = 1
? ? ? ? else:
? ? ? ? ? ? a_t[0] = 1? # do nothing
? ? ? ? # scale down epsilon
? ? ? ? # 縮小 epsilon
? ? ? ? if epsilon > FINAL_EPSILON and t > OBSERVE:
? ? ? ? ? ? epsilon -= (INITIAL_EPSILON - FINAL_EPSILON) / EXPLORE
? ? ? ? # 其次,執行選擇的動作,并保存返回的狀態、得分。
? ? ? ? x_t1_colored, r_t, terminal = game_state.frame_step(a_t)
? ? ? ? x_t1 = cv2.cvtColor(cv2.resize(x_t1_colored, (80, 80)), cv2.COLOR_BGR2GRAY)
? ? ? ? ret, x_t1 = cv2.threshold(x_t1, 1, 255, cv2.THRESH_BINARY)
? ? ? ? x_t1 = np.reshape(x_t1, (80, 80, 1))
? ? ? ? s_t1 = np.append(x_t1, s_t[:, :, :3], axis=2)
? ? ? ? # 經驗池保存的是以一個馬爾科夫序列于D中
? ? ? ? D.append((s_t, a_t, r_t, s_t1, terminal))
? ? ? ? # (s_t, a_t, r_t, s_t1, terminal)分別表示
? ? ? ? # t時的狀態s_t,
? ? ? ? # 執行的動作a_t,
? ? ? ? # 得到的反饋r_t,
? ? ? ? # 得到的下一步的狀態s_t1
? ? ? ? # 游戲是否結束的標志terminal
? ? ? ? # 如果經驗池超過最大長度 則彈出最早的經驗數據
? ? ? ? if len(D) > REPLAY_MEMORY:
? ? ? ? ? ? D.popleft()
? ? ? ? # 過了一段時間之后,t 是計數器
? ? ? ? if t > OBSERVE:
? ? ? ? ? ? minibatch = random.sample(D, BATCH)
? ? ? ? ? ? # 從經驗池D中隨機提取馬爾科夫序列
? ? ? ? ? ? s_j_batch = [d[0] for d in minibatch]
? ? ? ? ? ? a_batch = [d[1] for d in minibatch]
? ? ? ? ? ? r_batch = [d[2] for d in minibatch]
? ? ? ? ? ? s_j1_batch = [d[3] for d in minibatch]
? ? ? ? ? ? y_batch = []
? ? ? ? ? ? readout_j1_batch = readout.eval(feed_dict={s: s_j1_batch})
? ? ? ? ? ? for i in range(0, len(minibatch)):
? ? ? ? ? ? ? ? terminal = minibatch[i][4]
? ? ? ? ? ? ? ? if terminal:
? ? ? ? ? ? ? ? ? ? y_batch.append(r_batch[i])
? ? ? ? ? ? ? ? else:
? ? ? ? ? ? ? ? ? ? y_batch.append(r_batch[i] + GAMMA * np.max(readout_j1_batch[i]))
? ? ? ? ? ? train_step.run(feed_dict={
? ? ? ? ? ? ? ? y: y_batch,
? ? ? ? ? ? ? ? a: a_batch,
? ? ? ? ? ? ? ? s: s_j_batch}
? ? ? ? ? ? )
? ? ? ? s_t = s_t1
? ? ? ? t += 1
? ? ? ? # save progress every 10000 iterations
? ? ? ? if t % 10000 == 0:
? ? ? ? ? ? saver.save(sess, 'saved_networks/' + GAME + '-dqn', global_step=t)
? ? ? ? # print info
? ? ? ? state = ""
? ? ? ? if t <= OBSERVE:
? ? ? ? ? ? state = "observe"
? ? ? ? elif t > OBSERVE and t <= OBSERVE + EXPLORE:
? ? ? ? ? ? state = "explore"
? ? ? ? else:
? ? ? ? ? ? state = "train"
? ? ? ? print("TIMESTEP", t, "/ STATE", state, \
? ? ? ? ? ? ? "/ EPSILON", epsilon, "/ ACTION", action_index, "/ REWARD", r_t, \
? ? ? ? ? ? ? "/ Q_MAX %e" % np.max(readout_t))
? ? ? ? # write info to files
? ? ? ? '''
? ? ? ? if t % 10000 <= 100:
? ? ? ? ? ? a_file.write(",".join([str(x) for x in readout_t]) + '\n')
? ? ? ? ? ? h_file.write(",".join([str(x) for x in h_fc1.eval(feed_dict={s:[s_t]})[0]]) + '\n')
? ? ? ? ? ? cv2.imwrite("logs_tetris/frame" + str(t) + ".png", x_t1)
? ? ? ? '''
def playGame():
? ? sess = tf.InteractiveSession()
? ? s, readout, h_fc1 = createNetwork()
? ? trainNetwork(s, readout, h_fc1, sess)
def main():
? ? playGame()
if __name__ == "__main__":
? ? main()