以下代码存在无法求导反向传播的bug,请你修改:# 反向LSTM input_backward = torch.flip(input, [0]) outputs_backward = [] for t in range(input_backward.size(0)): x = input_backward[t] i = torch.sigmoid(torch.matmul(x, self.W_i_backward) + torch.matmul(h_backward[-1], self.U_i_backward) + self.b_i_backward) f = torch.sigmoid(torch.matmul(x, self.W_f_backward) + torch.matmul(h_backward[-1], self.U_f_backward) + self.b_f_backward) c_tilde = torch.tanh(torch.matmul(x, self.W_c_backward) + torch.matmul(h_backward[-1], self.U_c_backward) + self.b_c_backward) c_backward[-1] = f * c_backward[-1] + i * c_tilde o = torch.matmul(x, self.W_o_backward) + torch.matmul(h_backward[-1], self.U_o_backward) + self.b_o_backward o = torch.sigmoid(o) h_backward[-1] = o * torch.tanh(c_backward[-1]) outputs_backward.append(h_backward[-1]) outputs_backward = torch.flip(torch.stack(outputs_backward), [0])
时间: 2024-03-03 10:49:49 浏览: 109
pytorch中的自定义反向传播,求导实例
这段代码看起来没有明显的无法求导反向传播的 bug,但是如果存在问题的话可能是因为某些操作的输入没有进行 requires_grad=True 的设置。可以尝试添加以下代码,保证所有涉及到反向传播的张量都设置了 requires_grad=True:
```
input_backward.requires_grad_()
self.W_i_backward.requires_grad_()
self.U_i_backward.requires_grad_()
self.b_i_backward.requires_grad_()
self.W_f_backward.requires_grad_()
self.U_f_backward.requires_grad_()
self.b_f_backward.requires_grad_()
self.W_c_backward.requires_grad_()
self.U_c_backward.requires_grad_()
self.b_c_backward.requires_grad_()
self.W_o_backward.requires_grad_()
self.U_o_backward.requires_grad_()
self.b_o_backward.requires_grad_()
```
另外,如果在模型训练时发现该部分无法进行反向传播,可以尝试将该部分的代码放到 `torch.no_grad()` 中,避免该部分的梯度被累加。
```
with torch.no_grad():
input_backward = torch.flip(input, [0])
outputs_backward = []
for t in range(input_backward.size(0)):
x = input_backward[t]
i = torch.sigmoid(torch.matmul(x, self.W_i_backward) + torch.matmul(h_backward[-1], self.U_i_backward) + self.b_i_backward)
f = torch.sigmoid(torch.matmul(x, self.W_f_backward) + torch.matmul(h_backward[-1], self.U_f_backward) + self.b_f_backward)
c_tilde = torch.tanh(torch.matmul(x, self.W_c_backward) + torch.matmul(h_backward[-1], self.U_c_backward) + self.b_c_backward)
c_backward[-1] = f * c_backward[-1] + i * c_tilde
o = torch.matmul(x, self.W_o_backward) + torch.matmul(h_backward[-1], self.U_o_backward) + self.b_o_backward
o = torch.sigmoid(o)
h_backward[-1] = o * torch.tanh(c_backward[-1])
outputs_backward.append(h_backward[-1])
outputs_backward = torch.flip(torch.stack(outputs_backward), [0])
```
阅读全文