【发布时间】:2020-07-15 20:23:41
【问题描述】:
我是 Python 和 PyTorch 的学生和初学者。我有一个非常基本的神经网络,我遇到了上面提到的 RunTimeError。重现错误的代码是这样的:
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
import matplotlib.pyplot as plt
# Ensure Reproducibility
torch.manual_seed(0)
# Data Generation
x = torch.randn((100,1), requires_grad = True)
y = 1 + 2 * x + 0.3 * torch.randn(100,1)
# Shuffles the indices
idx = np.arange(100)
np.random.shuffle(idx)
# Uses first 80 random indices for train
train_idx = idx[:70]
# Uses the remaining indices for validation
val_idx = idx[70:]
# Generates train and validation sets
x_train, y_train = x[train_idx], y[train_idx]
x_val, y_val = x[val_idx], y[val_idx]
class OurFirstNeuralNetwork(nn.Module):
def __init__(self):
super(OurFirstNeuralNetwork, self).__init__()
# Here we "define" our Neural Network Architecture
self.fc1 = nn.Linear(1, 5)
self.non_linearity_fc1 = nn.ReLU()
self.fc2 = nn.Linear(5,1)
#self.non_linearity_fc2 = nn.ReLU()
def forward(self, x):
# The forward pass
# Here we define how activations "flow" between neurons. We've already discussed the "Sum" and "Transformation" steps of the forward pass.
sum_fc1 = self.fc1(x)
transformation_fc1 = self.non_linearity_fc1(sum_fc1)
sum_fc2 = self.fc2(transformation_fc1)
#transformation_fc2 = self.non_linearity_fc2(sum_fc2)
# The transformation_fc2 is also the output of our model which symbolises the end of our forward pass.
return sum_fc2
# Instantiate the model and train
model = OurFirstNeuralNetwork()
print(model)
print(model.state_dict())
n_epochs = 1000
loss_fn = nn.MSELoss(reduction='mean')
optimizer = optim.Adam(model.parameters())
for epoch in range(n_epochs):
model.train()
optimizer.zero_grad()
prediction = model(x_train)
loss = loss_fn(y_train, prediction)
print(epoch, loss)
loss.backward(retain_graph=True)
optimizer.step()
print(model.state_dict())
一切都是基本和标准的,而且效果很好。
但是,当我取出“retain_graph=True”参数时,它会抛出 RunTimeError。通过阅读各种论坛,我了解到这与第一次迭代后图表被丢弃有关,但我看过很多教程和博客,其中loss.backward() 是要走的路,特别是因为它可以节省内存。但我无法从概念上理解为什么这对我不起作用。
如果我提出问题的方式与预期格式不符,我们将不胜感激,我深表歉意。我愿意接受反馈,并有义务提供更多细节或重新表述问题,以便每个人都更容易。提前谢谢!
【问题讨论】:
标签: python machine-learning deep-learning pytorch