我正在尝试用pytorch复制代码。然而,我在自动评分功能上遇到了一些问题。我遇到了以下运行时错误。
RuntimeError:尝试第二次向后遍历图形
代码如下:
for epoch in range(num_epochs):
# Assuming the number of examples can be divided by the batch size, all
# the examples in the training data set are used once in one epoch
# iteration. The features and tags of mini-batch examples are given by X
# and y respectively
for X, y in data_iter(batch_size, features, labels):
print (X)
print (y)
l = loss(net(X,w,b) , y)
print (l)
l.backward(retain_graph=True)
print (w.grad)
print (b.grad)
with torch.no_grad():
w -= w.grad * 1e-5/batch_size
b -= b.grad * 1e-5/batch_size
w.grad.zero_()
b.grad.zero_()
有人能解释一下python中的autograd是如何工作的吗?如果有人能给我推荐一个学习pytorch的好资源,那就太好了。
发布于 2019-10-02 14:20:14
Pytorch的动态计算图形与Tensorflow有很大的不同。为了节省内存,Pytorch将删除grpah中不再使用的所有中间节点。也就是说,如果你想通过这些中间节点两次或更多地支持你的梯度,你将面临麻烦。
简单的解决方案是设置retain_graph=True
。例如,
model = Autoencoder()
rec = model(x)
loss_1 = mse_loss(rec, x)
loss_2 = l1_loss(rec, x)
opt.zero_grad()
loss_1.backward(retain_graph=True)
loss_2.backward()
opt.step()
https://stackoverflow.com/questions/58202580
复制相似问题