我为以前版本的PyTorch编写了代码,并收到第3行的2条警告:
import torch.nn.functional as F
def select_action(self, state):
probabilities = F.softmax(self.model(Variable(state, volatile = True))*100) # T=100
action = probs.multinomial(num_samples=1)
return action.data[0,0]UserWarning:挥发性物质被删除了,现在没有效果了。使用
with torch.no_grad():代替。 UserWarning:取消了对softmax的隐式尺寸选择。将调用更改为包含dim=X >作为参数。
我发现:
当您确信甚至不会调用.backward()时,建议在纯推理模式下使用易失性。它比任何其他的自动梯度设置更有效-它将使用绝对最小的内存量来评估模型。易失性还确定requires_grad是假的。
我说得对吗,我应该把它移除?因为我想得到概率,所以我应该使用dim=1吗?代码的第3行应该如下所示:
probabilities = F.softmax(self.model(Variable(state), dim=1)\*100) # T=100
在这里创建了状态:
def update(self, reward, new_signal):
new_state = torch.Tensor(new_signal).float().unsqueeze(0)
self.memory.push((self.last_state, new_state, torch.LongTensor([int(self.last_action)]), torch.Tensor([self.last_reward])))
action = self.select_action(new_state)
if len(self.memory.memory) > 100:
batch_state, batch_next_state, batch_action, batch_reward = self.memory.sample(100)
self.learn(batch_state, batch_next_state, batch_reward, batch_action)
self.last_action = action
self.last_state = new_state
self.last_reward = reward
self.reward_window.append(reward)
if len(self.reward_window) > 1000:
del self.reward_window[0]
return action发布于 2020-04-21 13:50:55
你是对的但不是“完全”对的。
除了前面提到的更改之外,您还应该使用torch.no_grad(),如下所示:
def select_action(self, state):
with torch.no_grad():
probabilities = F.softmax(self.model(state), dim=1)*100
action = probs.multinomial(num_samples=1)
return action.data[0,0]这个块关闭了它中代码的自动梯度引擎(所以您保存的内存类似于volatile)。
另外,请注意Variable也是不推荐的(请检查这里),state应该简单地使用requires_grad=True创建torch.tensor。
顺便说一下。您有probs和probabilities,但我认为这是相同的东西,只是一个错误。
发布于 2020-08-24 00:13:40
我在python 2.7中找到了相同的源代码--“自动驾驶汽车”应用程序。我无法为pytorch/pytorch-cpu安装python 2.7 (CUDA驱动程序问题.)因此,我必须修复在python 3.*中运行的代码。
下面是我为使其工作而更改的内容(包括上面其他人建议的更改):更新select_action和learn类的Dqn函数,如下所示:
def select_action(self, state):
with torch.no_grad():
probs = F.softmax(self.model(state) * 100, dim=1) # T=100
action = probs.multinomial(num_samples=1)
return action.data[0, 0]
def learn(self, batch_state, batch_next_state, batch_reward, batch_action):
outputs = self.model(batch_state).gather(1, batch_action.unsqueeze(1)).squeeze(1)
next_outputs = self.model(batch_next_state).detach().max(1)[0]
target = self.gamma * next_outputs + batch_reward
td_loss = F.smooth_l1_loss(outputs, target)
self.optimizer.zero_grad()
td_loss.backward()
self.optimizer.step()https://stackoverflow.com/questions/61333684
复制相似问题