求参数w进行求解梯度有两种方式1.
mse.backward()
w.grad
方式2.
torch.autograd.grad(mse,[w])
#损失函数的梯度
import torch import torch.nn.functional as F x=torch.ones(1) w=torch.full([1],2) mse=F.mse_loss(torch.ones(1),x*w) w.requires_grad_() mse=F.mse_loss(torch.ones(1),x*w) #第一种方式 mse.backward() w.grad 第二种方式 torch.autograd.grad(mse,[w])
#计算softmax函数 import torch import torch.nn.functional as F a=torch.rand(3) p=F.softmax(a,dim=0) a.requires_grad_() p=F.softmax(a,dim=0) torch.autograd.grad(p[2],[a],retain_graph=True)
import torch import torch.nn.functional as F x=torch.randn(1,10) w=torch.randn(2,10,requires_grad=True) o=torch.sigmoid(x@w.t()) o.shape loss=F.mse_loss(torch.ones(1,2),o) loss.backward() w.grad
原文:https://www.cnblogs.com/cmybky/p/12161698.html