当.grad具有正确的值时,autograd.grad始终不返回任何值

时间:2020-06-30 14:36:02

标签: python machine-learning pytorch

这是一个简单的多项式回归程序,我尝试通过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)

0 个答案:

没有答案