如何解决CNN-RNN - 如何管理梯度?
我正在尝试创建一个可以执行动作识别的系统。我正在尝试使用 CNN 和 RNN 的组合。对于 CNN,我使用的是 ShuffleNet v2。我用我的自定义 fc
替换了模型的 nn.Sequential
:
rcnn_layer = nn.Sequential(
nn.Linear(1024,128),View((1,128)),InputModifier(10),nn.RNN(input_size=128,hidden_size=64),GetLastHidden(),nn.Linear(64,3),nn.Softmax(dim=-1)
)
自定义类是:
View
- 重塑第一个线性层的输出,使其适合 RNN
InputModifier
- 保留模型的先前输出
GetLastHidden
- 返回 RNN 的最后一层
将来我想在手机上使用该模型(不知何故),所以我正在努力使其尽可能高效。因此,为了让它运行得更快,在我的 InputModifier
类中,我保留了 CNN 以前的输出。代码如下:
class InputModifier(nn.Module):
prev = []
def __init__(self,max_seq_len):
assert max_seq_len != 0,'`max_seq_len` cannot be 0.'
super(InputModifier,self).__init__()
self.max_seq_len = max_seq_len
def forward(self,x):
self.prev.append(x)
if self.max_seq_len > 0:
self.prev = self.prev[-self.max_seq_len:]
inp = torch.cat(self.prev)
return inp
问题是:我不知道如何让它工作。当我运行 loss.backward()
时,出现 RuntimeError: Trying to backward through the graph a second time,but the saved intermediate results have already been freed.
错误。
如果我设置了 loss.backward(retain_graph=True)
,我会得到 RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [1024,128]],which is output 0 of TBackward,is at version 2; expected version 1 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient,with torch.autograd.set_detect_anomaly(True).
。
PS:训练代码:
model = model.to(device)
optim = torch.optim.Adam(lr=0.01,params=model.parameters())
criterion = nn.CrossEntropyLoss()
model.train()
for i,(img,c) in enumerate(dataloader):
out = model(img)
loss = criterion(out,c.view(1))
optim.zero_grad()
loss.backward()
optim.step()
欢迎所有建议。谢谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。