仍在通过视频教程https://www.youtube.com/watch?v=weQ5pShEVic&list=PLbMqOoYQ3Mxw1Sl5iAAV4SJmvnAGAhFvK&index=2关于pytorch的工作,但遇到另一个错误。
lossFunc = torch.nn.MSELoss()
for i in range(epoch):
output = net(x)
loss = lossFunc(output, y)
loss.zero_grad()
loss.backward()
for f in net.parameters():
f.data.sub_(learning_rate = f.grad.data)
print(output, loss)
创建了网络、损失函数,并希望在反向传播之前进行迭代
但得到以下错误:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/var/folders/v_/yq26pm194xj5ckqy8p_njwc00000gn/T/ipykernel_9995/2476130544.py in <module>
3 output = net(x)
4 loss = lossFunc(output, y)
----> 5 loss.zero_grad()
6 loss.backward()
7
AttributeError: 'Tensor' object has no attribute 'zero_grad'
怎么回事?
1条答案
按热度按时间ttisahbt1#
您应该为优化器使用零梯度。