梯度计算

求参数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)
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/cmybky/p/12161698.html