I got thiserror “RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn” when I run this simple code. I don’t know what the problem is?
def cost(params, Y):
res = [myNetwork(params)]
return square_loss(res, Y)
def square_loss(res, Y):
loss = 0
for l, p in zip(res, Y):
loss += (l - p) ** 2
loss = loss / len(Y)
loss = torch.from_numpy(loss)
return torch.mean(loss)
var1 = Variable(torch.tensor([0.2]), requires_grad=True)
opt = torch.optim.Adam([var1], lr=0.1)
print(cost(var1, Y))
for i in range(100):
opt.zero_grad()
loss = cost(var1, Y)
loss.backward()
opt.step()
print(“Cost:”, loss)