首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Keras代码错误- Q-learning OpenAI健身房FrozenLake

Keras代码错误- Q-learning OpenAI健身房FrozenLake
EN

Stack Overflow用户
提问于 2017-08-25 03:57:33
回答 1查看 683关注 0票数 6

也许我的问题看起来很愚蠢。

我正在研究Q学习算法。为了更好地理解它,我正在尝试将this FrozenLake示例的Tenzorflow代码重新编写为Keras代码。

我的代码:

代码语言:javascript
复制
import gym
import numpy as np
import random

from keras.layers import Dense
from keras.models import Sequential
from keras import backend as K    

import matplotlib.pyplot as plt
%matplotlib inline

env = gym.make('FrozenLake-v0')

model = Sequential()
model.add(Dense(16, activation='relu', kernel_initializer='uniform', input_shape=(16,)))
model.add(Dense(4, activation='softmax', kernel_initializer='uniform'))

def custom_loss(yTrue, yPred):
    return K.sum(K.square(yTrue - yPred))

model.compile(loss=custom_loss, optimizer='sgd')

# Set learning parameters
y = .99
e = 0.1
#create lists to contain total rewards and steps per episode
jList = []
rList = []

num_episodes = 2000
for i in range(num_episodes):
    current_state = env.reset()
    rAll = 0
    d = False
    j = 0
    while j < 99:
        j+=1

        current_state_Q_values = model.predict(np.identity(16)[current_state:current_state+1], batch_size=1)
        action = np.reshape(np.argmax(current_state_Q_values), (1,))

        if np.random.rand(1) < e:
            action[0] = env.action_space.sample() #random action

        new_state, reward, d, _ = env.step(action[0])

        rAll += reward
        jList.append(j)
        rList.append(rAll)

        new_Qs = model.predict(np.identity(16)[new_state:new_state+1], batch_size=1)
        max_newQ = np.max(new_Qs)

        targetQ = current_state_Q_values
        targetQ[0,action[0]] = reward + y*max_newQ
        model.fit(np.identity(16)[current_state:current_state+1], targetQ, verbose=0, batch_size=1)
        current_state = new_state

        if d == True:
            #Reduce chance of random action as we train the model.
            e = 1./((i/50) + 10)
            break
print("Percent of succesful episodes: " + str(sum(rList)/num_episodes) + "%")

当我运行它时,它不能很好地工作:成功剧集的百分比: 0.052%

代码语言:javascript
复制
plt.plot(rList)

original Tensorflow code更好:成功剧集的百分比: 0.352%

代码语言:javascript
复制
plt.plot(rList)

我做错了什么?

EN

回答 1

Stack Overflow用户

发布于 2018-04-04 09:29:10

除了在评论中提到的@Maldus设置use_bias=False之外,你可以尝试的另一件事是从更高的epsilon值开始(例如0.5,0.75)?一个技巧可能是只在达到目标时降低epsilon值。也就是说,不要在每一集的结尾减少epsilon。这样你的玩家就可以继续随机探索地图,直到它开始在一条好的路线上收敛,然后减少epsilon参数将是一个好主意。

实际上,我在这个gist中使用卷积层而不是密集层在keras中实现了一个类似的模型。设法让它在不到2000集的情况下工作。可能会对其他人有所帮助:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45869939

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档