python - 计算策略梯度的损失
问题描述
我正在尝试使用 SeqGAN 的策略梯度来实现损失。如果我们在函数中执行此操作,我知道参数将是input
、target
和rewards
。这些是参数的尺寸:
- 输入:(批量大小 x 序列长度)
- 目标:(批量大小 x 序列长度)
- 奖励:(1 x 批量大小)
def batchPGLoss(self, inp: torch.Tensor, target: torch.Tensor, reward: List) -> torch.Tensor:
batch_size, seq_len = inp.size()
# swap the dimensions
inp = inp.permute(1, 0) # (seq_len x batch_size)
# swap the dimensions
target = target.permute(1, 0) # (seq_len x batch_size)
# init hidden state
h = self.init_hidden(batch_size)
loss = torch.zeros(1)
for i in range(seq_len):
# pass the first tokens for each elem in batch
out, h = self.forward(inp[i], h)
for j in range(batch_size):
loss += -out[j][target.data[i][j]] * reward[j] # log(P(y_t | Y_1, ..., Y_{t-1})) * Q
return loss / batch_size
当我运行它时,我得到以下问题
RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
我检查了哪个部分给出了错误,我发现这-out[j][target.data[i][j]]
是问题所在,因为它需要渐变。我可以使用tensor.detach().numpy()
,但这并不能解决问题,因为我仍然需要保持out
在图表上
有什么建议么?
解决方案
推荐阅读
- python - 截断熊猫数据框中的行数
- bash - 如何使用 Expect 从 URL 运行文件?
- python - 如何加速 Pandas .to_sql 函数?
- jquery - 所选字段未填充预定义的 selectedOptions
- shell - 为什么我的脚本在缩进后会失败?
- javascript - a-frame 不会加载自己的 3d 模型
- python - anaconda 的 Mpi 安装失败
- java - Cloud Firestore 通过引用从另一个集合获取集合
- excel - 将最后一行编号添加到 VBA 中的 excel 公式
- sql - 将 ROW_NUMBER() 与派生表一起使用