[英]How do you create Deep Q-Learning neural network to solve simple games like snake?
最近四天我一直在努力嘗試創建一個簡單的可學習的神經網絡(NN)。 我從河內塔樓開始,但是那很棘手(可以通過Q表完成),沒有人在網上真的有很好的示例,因此我決定改為在蛇游戲中使用它,因為那里有很多示例和教程。 長話短說,我做了一個新的超級簡單的游戲,您有[0,0,0,0],通過選擇0、1、2或3,您可以將0更改為1,反之亦然。 因此,選擇1將給出[0,1,0,0]的輸出,而再次選擇1將返回到[0,0,0,0]。 很容易
盡管游戲非常簡單,但由於我沒有編碼方面的知識,所以我仍然很難從概念到實際。
現在的最終目標是獲得下面的代碼,以便能夠多次完成游戲。 (它目前已經運行了約600次,並且沒有一次完成4步問題)
當前的網絡體系結構是第一個隱藏層中的4個輸入4個節點和4個輸出,即使隱藏層是冗余的,我也希望保持這種方式,以便我可以學習如何正確處理其他問題。
如果您不願意閱讀代碼,但我不怪您,請把我的心理偽代碼放在這里:
import tensorflow as tf ## importing libraries
import random
import numpy as np
epsilon = 0.1 ## create non tf variables
y = 0.4
memory = []
memory1 = []
input_ = tf.placeholder(tf.float32, [None, 4], name='input_')
W1 = tf.Variable(tf.random_normal([4, 4], stddev=0.03), name='W1')
b1 = tf.Variable(tf.random_normal([4]), name='b1')
hidden_out = tf.add(tf.matmul(input_, W1), b1, name='hidden_out') ## W for weights
hidden_out = tf.nn.relu(hidden_out) ## b for bias'
W2 = tf.Variable(tf.random_normal([4, 4], stddev=0.03), name='W2')
b2 = tf.Variable(tf.random_normal([4]), name='b2')
Qout = tf.add(tf.matmul(hidden_out, W2), b2, name='Qout')
sig_out = tf.sigmoid(Qout, name='out')
Q_target = tf.placeholder(shape=(None,4), dtype=tf.float32)
loss = tf.reduce_sum(tf.square(Q_target - Qout))
optimiser = tf.train.GradientDescentOptimizer(learning_rate=y).minimize(loss)
init_op = tf.global_variables_initializer()
with tf.compat.v1.Session() as sess:
sess.run(init_op)
for epoch in range(200): ## run game 200 times
states = [0,0,0,0]
for _ in range(20): ## 20 turns to do the correct 4 moves
if _ == 19:
memory1.append(states)
output = np.argmax(sess.run(sig_out, feed_dict={input_: [states]}))
## sig_out is the output put through a sigmoid function
if random.random() < epsilon: ## this is the code for the game
output = random.randint(0,3) ## ...
if states[output] == 0: ## ...
states[output] = 1 ## ...
else: ## ...
states[output] = 0 ## ...
reward = states
Qout1 = sess.run(sig_out, feed_dict={input_: [states]})
target = [reward + y*np.max(Qout1)]
sess.run([optimiser,loss], feed_dict={input_: [states], Q_target: target})
我有一段時間沒有收到任何錯誤消息了,理想情況下,每次的實際結果都是[1,1,1,1]。
預先感謝您的所有幫助
ps我沒想到這個客觀的稱呼,對不起
reward
值應該是采取行動后的目標值。 在您的情況下,您設置了reward=states
。 由於您的功能正在嘗試最大化回報,因此您的狀態越接近[1,1,1,1],您的AI應獲得的獎勵就越多。
也許諸如reward = sum(states)
類的獎勵函數將解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.