- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
您好,我正在尝试训练 DQN 来解决健身房的 Cartpole 问题。出于某种原因 Loss看起来像这样(橙色线)。你们能看看我的代码并帮助解决这个问题吗?我对超参数进行了一些尝试,所以我认为它们不是这里的问题。
class DQN(nn.Module):
def __init__(self, input_dim, output_dim):
super(DQN, self).__init__()
self.linear1 = nn.Linear(input_dim, 16)
self.linear2 = nn.Linear(16, 32)
self.linear3 = nn.Linear(32, 32)
self.linear4 = nn.Linear(32, output_dim)
def forward(self, x):
x = F.relu(self.linear1(x))
x = F.relu(self.linear2(x))
x = F.relu(self.linear3(x))
return self.linear4(x)
final_epsilon = 0.05
initial_epsilon = 1
epsilon_decay = 5000
global steps_done
steps_done = 0
def select_action(state):
global steps_done
sample = random.random()
eps_threshold = final_epsilon + (initial_epsilon - final_epsilon) * \
math.exp(-1. * steps_done / epsilon_decay)
if sample > eps_threshold:
with torch.no_grad():
state = torch.Tensor(state)
steps_done += 1
q_calc = model(state)
node_activated = int(torch.argmax(q_calc))
return node_activated
else:
node_activated = random.randint(0,1)
steps_done += 1
return node_activated
class ReplayMemory(object): # Stores [state, reward, action, next_state, done]
def __init__(self, capacity):
self.capacity = capacity
self.memory = [[],[],[],[],[]]
def push(self, data):
"""Saves a transition."""
for idx, point in enumerate(data):
#print("Col {} appended {}".format(idx, point))
self.memory[idx].append(point)
def sample(self, batch_size):
rows = random.sample(range(0, len(self.memory[0])), batch_size)
experiences = [[],[],[],[],[]]
for row in rows:
for col in range(5):
experiences[col].append(self.memory[col][row])
return experiences
def __len__(self):
return len(self.memory[0])
input_dim, output_dim = 4, 2
model = DQN(input_dim, output_dim)
target_net = DQN(input_dim, output_dim)
target_net.load_state_dict(model.state_dict())
target_net.eval()
tau = 2
discount = 0.99
learning_rate = 1e-4
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
memory = ReplayMemory(65536)
BATCH_SIZE = 128
def optimize_model():
if len(memory) < BATCH_SIZE:
return 0
experiences = memory.sample(BATCH_SIZE)
state_batch = torch.Tensor(experiences[0])
action_batch = torch.LongTensor(experiences[1]).unsqueeze(1)
reward_batch = torch.Tensor(experiences[2])
next_state_batch = torch.Tensor(experiences[3])
done_batch = experiences[4]
pred_q = model(state_batch).gather(1, action_batch)
next_state_q_vals = torch.zeros(BATCH_SIZE)
for idx, next_state in enumerate(next_state_batch):
if done_batch[idx] == True:
next_state_q_vals[idx] = -1
else:
# .max in pytorch returns (values, idx), we only want vals
next_state_q_vals[idx] = (target_net(next_state_batch[idx]).max(0)[0]).detach()
better_pred = (reward_batch + next_state_q_vals).unsqueeze(1)
loss = F.smooth_l1_loss(pred_q, better_pred)
optimizer.zero_grad()
loss.backward()
for param in model.parameters():
param.grad.data.clamp_(-1, 1)
optimizer.step()
return loss
points = []
losspoints = []
#save_state = torch.load("models/DQN_target_11.pth")
#model.load_state_dict(save_state['state_dict'])
#optimizer.load_state_dict(save_state['optimizer'])
env = gym.make('CartPole-v0')
for i_episode in range(5000):
observation = env.reset()
episode_loss = 0
if episode % tau == 0:
target_net.load_state_dict(model.state_dict())
for t in range(1000):
#env.render()
state = observation
action = select_action(observation)
observation, reward, done, _ = env.step(action)
if done:
next_state = [0,0,0,0]
else:
next_state = observation
memory.push([state, action, reward, next_state, done])
episode_loss = episode_loss + float(optimize_model(i_episode))
if done:
points.append((i_episode, t+1))
print("Episode {} finished after {} timesteps".format(i_episode, t+1))
print("Avg Loss: ", episode_loss / (t+1))
losspoints.append((i_episode, episode_loss / (t+1)))
if (i_episode % 100 == 0):
eps = final_epsilon + (initial_epsilon - final_epsilon) * \
math.exp(-1. * steps_done / epsilon_decay)
print(eps)
if ((i_episode+1) % 5001 == 0):
save = {'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict()}
torch.save(save, "models/DQN_target_" + str(i_episode // 5000) + ".pth")
break
env.close()
x = [coord[0] * 100 for coord in points]
y = [coord[1] for coord in points]
x2 = [coord[0] * 100 for coord in losspoints]
y2 = [coord[1] for coord in losspoints]
plt.plot(x, y)
plt.plot(x2, y2)
plt.show()
我基本上遵循了 pytorch 的教程,除了使用 env 返回的状态而不是像素。我还更改了重播内存,因为我在那里遇到了问题。除此以外,其他一切都几乎保持不变。
编辑:
我尝试在小批量上过度拟合,损失看起来像 this不更新目标网络和this更新的时候
编辑 2:
这绝对是目标网络的问题,我尝试删除它并且损失似乎没有呈指数增长
最佳答案
您的tau
值太小,目标网络更新太小导致DQN 训练不稳定。您可以尝试使用 1000(OpenAI Baseline 的 DQN 示例)或 10000(Deepmind 的 Nature 论文)。
在 Deepmind 的 2015 年 Nature 论文中,它指出:
The second modification to online Q-learning aimed at further improving the stability of our method with neural networks is to use a separate network for generating the traget yj in the Q-learning update. More precisely, every C updates we clone the network Q to obtain a target network Q' and use Q' for generating the Q-learning targets yj for the following C updates to Q. This modification makes the algorithm more stable compared to standard online Q-learning, where an update that increases Q(st,at) often also increases Q(st+1, a) for all a and hence also increases the target yj, possibly leading to oscillations or divergence of the policy. Generating the targets using the older set of parameters adds a delay between the time an update to Q is made and the time the update affects the targets yj, making divergence or oscillations much more unlikely.
Human-level control through deep reinforcementlearning, Mnih et al., 2015
我已经使用 tau=2
、tau=10
、tau=100
、tau= 的设置运行了您的代码1000
和 tau=10000
。 tau=100
的更新频率解决了这个问题(达到最大步数 200)。
tau=2
以下是您的代码的修改版本。
import random
import math
import matplotlib.pyplot as plt
import torch
from torch import nn
import torch.nn.functional as F
import gym
class DQN(nn.Module):
def __init__(self, input_dim, output_dim):
super(DQN, self).__init__()
self.linear1 = nn.Linear(input_dim, 16)
self.linear2 = nn.Linear(16, 32)
self.linear3 = nn.Linear(32, 32)
self.linear4 = nn.Linear(32, output_dim)
def forward(self, x):
x = F.relu(self.linear1(x))
x = F.relu(self.linear2(x))
x = F.relu(self.linear3(x))
return self.linear4(x)
final_epsilon = 0.05
initial_epsilon = 1
epsilon_decay = 5000
global steps_done
steps_done = 0
def select_action(state):
global steps_done
sample = random.random()
eps_threshold = final_epsilon + (initial_epsilon - final_epsilon) * \
math.exp(-1. * steps_done / epsilon_decay)
if sample > eps_threshold:
with torch.no_grad():
state = torch.Tensor(state)
steps_done += 1
q_calc = model(state)
node_activated = int(torch.argmax(q_calc))
return node_activated
else:
node_activated = random.randint(0,1)
steps_done += 1
return node_activated
class ReplayMemory(object): # Stores [state, reward, action, next_state, done]
def __init__(self, capacity):
self.capacity = capacity
self.memory = [[],[],[],[],[]]
def push(self, data):
"""Saves a transition."""
for idx, point in enumerate(data):
#print("Col {} appended {}".format(idx, point))
self.memory[idx].append(point)
def sample(self, batch_size):
rows = random.sample(range(0, len(self.memory[0])), batch_size)
experiences = [[],[],[],[],[]]
for row in rows:
for col in range(5):
experiences[col].append(self.memory[col][row])
return experiences
def __len__(self):
return len(self.memory[0])
input_dim, output_dim = 4, 2
model = DQN(input_dim, output_dim)
target_net = DQN(input_dim, output_dim)
target_net.load_state_dict(model.state_dict())
target_net.eval()
tau = 100
discount = 0.99
learning_rate = 1e-4
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
memory = ReplayMemory(65536)
BATCH_SIZE = 128
def optimize_model():
if len(memory) < BATCH_SIZE:
return 0
experiences = memory.sample(BATCH_SIZE)
state_batch = torch.Tensor(experiences[0])
action_batch = torch.LongTensor(experiences[1]).unsqueeze(1)
reward_batch = torch.Tensor(experiences[2])
next_state_batch = torch.Tensor(experiences[3])
done_batch = experiences[4]
pred_q = model(state_batch).gather(1, action_batch)
next_state_q_vals = torch.zeros(BATCH_SIZE)
for idx, next_state in enumerate(next_state_batch):
if done_batch[idx] == True:
next_state_q_vals[idx] = -1
else:
# .max in pytorch returns (values, idx), we only want vals
next_state_q_vals[idx] = (target_net(next_state_batch[idx]).max(0)[0]).detach()
better_pred = (reward_batch + next_state_q_vals).unsqueeze(1)
loss = F.smooth_l1_loss(pred_q, better_pred)
optimizer.zero_grad()
loss.backward()
for param in model.parameters():
param.grad.data.clamp_(-1, 1)
optimizer.step()
return loss
points = []
losspoints = []
#save_state = torch.load("models/DQN_target_11.pth")
#model.load_state_dict(save_state['state_dict'])
#optimizer.load_state_dict(save_state['optimizer'])
env = gym.make('CartPole-v0')
for i_episode in range(5000):
observation = env.reset()
episode_loss = 0
if i_episode % tau == 0:
target_net.load_state_dict(model.state_dict())
for t in range(1000):
#env.render()
state = observation
action = select_action(observation)
observation, reward, done, _ = env.step(action)
if done:
next_state = [0,0,0,0]
else:
next_state = observation
memory.push([state, action, reward, next_state, done])
episode_loss = episode_loss + float(optimize_model())
if done:
points.append((i_episode, t+1))
print("Episode {} finished after {} timesteps".format(i_episode, t+1))
print("Avg Loss: ", episode_loss / (t+1))
losspoints.append((i_episode, episode_loss / (t+1)))
if (i_episode % 100 == 0):
eps = final_epsilon + (initial_epsilon - final_epsilon) * \
math.exp(-1. * steps_done / epsilon_decay)
print(eps)
if ((i_episode+1) % 5001 == 0):
save = {'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict()}
torch.save(save, "models/DQN_target_" + str(i_episode // 5000) + ".pth")
break
env.close()
x = [coord[0] * 100 for coord in points]
y = [coord[1] for coord in points]
x2 = [coord[0] * 100 for coord in losspoints]
y2 = [coord[1] for coord in losspoints]
plt.plot(x, y)
plt.plot(x2, y2)
plt.show()
这是您的绘图代码的结果。
关于python - 使用 DQN 增加 Cartpole-v0 损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56964657/
我正在尝试使用 keras 在 Python 中编写自己的 DQN。我认为我的逻辑是正确的。我正在 CartPole 环境中尝试,但奖励在 50,000 集后并没有增加。任何帮助将不胜感激。目前我不关
我一直在尝试使用本文中的 DQN 解决 OpenAI 登月游戏 https://arxiv.org/pdf/2006.04938v2.pdf 问题是训练 50 集需要 12 个小时,所以一定是出了什么
我有一个或多或少标准的 DQN 实现来解决 Atari“Breakout”(来自 Coursera 强化学习类(class)),它在不同的计算机上表现完全不同: 在我的笔记本电脑上它收敛每次我运行它
QLearning方法有着明显的局限性,当状态和动作空间是离散的且维数不高时可使用Q-Table存储每个状态动作的Q值,而当状态和动作时高维连续时,该方法便不太适用。可以将Q-Table的更新问题变
对于强化学习,我读到张量板并不理想,因为它提供了每集和/或步骤的输入。由于强化学习有数千个步骤,因此它并没有给我们内容的概述。我在这里看到了这个修改后的张量板类:https://pythonprogr
对于强化学习,我读到张量板并不理想,因为它提供了每集和/或步骤的输入。由于强化学习有数千个步骤,因此它并没有给我们内容的概述。我在这里看到了这个修改后的张量板类:https://pythonprogr
我创建了一个深度 Q 网络来玩贪吃蛇。该代码运行良好,但在训练周期中性能并未真正提高。最后,它与采取随机操作的代理几乎没有区别。这是训练代码: def train(self): sel
编辑:以下似乎也是 FrozenLake-v0 的情况.请注意,我对简单的 Q 学习不感兴趣,因为我想看到适用于连续观察空间的解决方案。 我最近创建了 banana_gym OpenAI 环境。场景如
我正在使用 DQN 算法在我的环境中训练代理,如下所示: 代理通过选择离散 Action (左、右、上、下)来控制汽车 目标是以理想的速度行驶而不会撞到其他汽车 状态包含代理的汽车和周围汽车的速度和位
我正在实现简单的 DQN算法使用 pytorch , 解决来自 gym 的 CartPole 环境.我已经调试了一段时间,我无法弄清楚为什么模型没有学习。 观察: 使用 SmoothL1Loss性能比
我正在尝试构建一个可以学习玩游戏的深度 Q 网络 (DQN) 代理 2048 。我正在关注基于蛇游戏的其他程序和文章,并且效果很好( specifically this one )。 作为输入状态,我
我的任务涉及大型网格世界类型的环境(网格大小可能为 30x30、50x50、100x100,最大为 200x200)。该网格中的每个元素包含 0 或 1,它们在每个情节中随机初始化。我的目标是训练一个
我正在改编 Tabor 的 DQN 类(class) (https://github.com/philtabor/Deep-Q-Learning-Paper-To-Code) 中的 Pytorch 代
我正在使用 keras 构建 DQN,并使用具有经验回放内存的经典 DQN 算法对其进行训练。由于在 dqn 中,您需要多次调用 model.fit,这意味着每次从重播内存中采样批量数据时,使用 ke
我正在改编 Tabor 的 DQN 类(class) (https://github.com/philtabor/Deep-Q-Learning-Paper-To-Code) 中的 Pytorch 代
鉴于 OpenAI Gym 环境 MountainCar-v0总是返回 -1.0 作为奖励(即使目标实现了),我不明白 DQN 与经验回放如何收敛,但我知道它会收敛,因为我有 working code
我正在训练 DQN 来玩 OpenAI 的 Atari 环境,但我的网络的 Q 值迅速爆炸,远高于现实水平。 这是代码的相关部分: for state, action, reward, next_st
我最近开始研究神经网络。我目前正在试验 DQN。我已经能够让他们使用大量的 Atari 教程,但发现我无法理解整个问题,所以我为 DQN 编写了一个简单的模式来处理它只是 A 比 B 大,如果不是,则
您好,我正在尝试训练 DQN 来解决健身房的 Cartpole 问题。出于某种原因 Loss看起来像这样(橙色线)。你们能看看我的代码并帮助解决这个问题吗?我对超参数进行了一些尝试,所以我认为它们不是
所以我一直在关注 DQN 代理示例/教程,并按照示例中的方式进行设置,唯一的区别是我构建了自己的自定义 python 环境,然后将其包装在 TensorFlow 中。然而,无论我如何塑造我的观察和行动
我是一名优秀的程序员,十分优秀!