你需要使用
dtype=torch.float
:
import torch
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()
# option 1
out.backward()
print(x.grad)
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()
#option 2. Replace! do not leave one after the other
out.backward(torch.tensor(1, dtype=torch.float))
print(x.grad)
tensor([[ 4.5000, 4.5000],
[ 4.5000, 4.5000]])
tensor([[ 4.5000, 4.5000],
[ 4.5000, 4.5000]])