我正在试验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()
out
是:
我的目标是通过使用out
的梯度来调整W
,使W
接近0(在[-.00001 , 0.0001]
的间隔内)。
从这里开始,我该如何用火把来达到这个目的呢?
更新
@Umang:当我运行您建议的代码时,这就是我得到的结果:
事实上,算法是有分歧的。
发布于 2020-01-14 01:18:00
# 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)
我们定义了一个损失函数,使得它的最小值在期望的点上,并运行梯度下降。在这里,我使用了平方误差,但您也可以使用其他损失函数与期望的最小。
https://stackoverflow.com/questions/59727904
复制相似问题