这是一个简单的多项式回归程序,我尝试通过autograd.grad获得多项式的梯度,但它始终不返回任何值。主要问题可能是由火车
功能引起的这是我的代码:
import torch
import torch.autograd
import numpy as np
def target_fun(x):
return x*x + 2*x + 1
class polynomial:
def __init__(self,d):
self.dim = d
self.weight = torch.rand(d).float()
def Train(self,x,y):
self.weight.requires_grad_(True)
x = x.float()
y = y.float()
ty = torch.zeros(x.size(0))
for i in range(self.dim):
ty += self.weight[i]*x.pow(i)
E = (y - ty).norm(2).float()
E.backward()
grad_I = (torch.autograd.grad(E,self.weight.double(),create_graph = True, allow_unused = True))
print(self.weight.grad,"\n",grad_I)
x = np.linspace(-10,10,10)
x = torch.tensor(x).double()
y = target_fun(x)
po = polynomial(6)
po.Train(x,y)