PyTorch与梯度下降

对于逻辑回归而言,交叉熵是损失函数,softmax是激活函数。
from torch.nn import functional as F

PyTorch求导的两种方式

torch.autograd.grad(loss, [w1, w2])
返回值为[w1 grad, w2 grad]

loss.backward()
w1.grad()获得w1的梯度值,w2.grad()获得w2的梯度值。

x = torch.ones(1)
w = torch.full((1,), 2, requires_grad = True)
mse = F.mse_loss(x*w, torch.ones(1))
torch.autograd.grad(mse, w)

以一元线性回归为例:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([1., 2., 3., 4., 5.], dtype = np.float32)
y = np.array([1., 3., 2., 3., 5.], dtype = np.float32)

x = torch.from_numpy(x)
y = torch.from_numpy(y)

  需要注意的是,numpy中的浮点型默认类型为double。而Pytorch中的浮点型默认类型为FloatTensor。

w = torch.rand(1, requires_grad=True)
b = torch.rand(1, requires_grad=True)

loss = F.mse_loss(x*w+b, y)
loss.backward()

print(w.grad)
print(b.grad)

反向传播的链式法则

  要注意的是,例如w1,w2的梯度,grad_w1和grad_w2要保证它们的维度相匹配,所以有时候就要适当的增加转置运算(T)。

猜你喜欢

转载自blog.csdn.net/weixin_47532216/article/details/121589259