Python 3.x 用反向传播和梯度下降法求PyTorch中的参数

Python 3.x 用反向传播和梯度下降法求PyTorch中的参数,python-3.x,pytorch,gradient-descent,backpropagation,Python 3.x,Pytorch,Gradient Descent,Backpropagation,我正在试验PyTorch、自微分和梯度下降 为此,我想估算参数,这些参数将在参数函数中产生一个任意线性的特定值 我的代码在这里: import torch X = X.astype(float) X = np.array([[3.], [4.], [5.]]) X = torch.from_numpy(X) X.requires_grad = True W = np.random.randn(3,3) W = np.triu(W, k=0) W = torch.from_numpy

我正在试验PyTorch、自微分和梯度下降

为此,我想估算参数,这些参数将在参数函数中产生一个任意线性的特定值

我的代码在这里:

import torch

X = X.astype(float)

X = np.array([[3.], [4.], [5.]])

X = torch.from_numpy(X)

X.requires_grad = True

W = np.random.randn(3,3)

W = np.triu(W, k=0)

W = torch.from_numpy(W)

W.requires_grad = True

out = 10 - (X@torch.transpose(X, 1,0) * W).sum()
我们的目标是:

我的目标是在[-.00001,0.0001]的区间内,通过使用W的梯度调整W,得出接近0的值

我应该如何从这里开始,用pytorch实现这一目标

使现代化 @Umang:这就是我运行您建议的代码时得到的结果:

事实上,算法是有分歧的

# your code as it is
import torch
import numpy as np 

X = np.array([[3.], [4.], [5.]])
X = torch.from_numpy(X)
X.requires_grad = True
W = np.random.randn(3,3)
W = np.triu(W, k=0)
W = torch.from_numpy(W)
W.requires_grad = True

# define parameters for gradient descent
max_iter=100
lr_rate = 1e-3

# we will do gradient descent for max_iter iteration, or convergence till the criteria is met.
i=0
out = compute_out(X,W)
while (i<max_iter) and (torch.abs(out)>0.01):
    loss = (out-0)**2
    W = W - lr_rate*torch.autograd.grad(loss, W)[0]
    i+=1
    print(f"{i}: {out}")
    out = compute_out(X,W)

print(W)

我们定义了一个损失函数,使得它的极小值在期望点,并运行梯度下降。在这里,我使用了平方误差,但是你也可以使用其他的损失函数和期望的最小值

对不起!没有意识到你想要接近0,修正了它