七 自动微分
torch.autograd模块:自动微分模块,自动计算张量操作的梯度,可以自动求导实现权重参数的更新
1 基础概念
张量:Torch中的一切都是张量,属性requires_grad决定是否对其进行梯度计算,True为进行梯度计算
计算图:torch.autograd通过创建一个动态计算图来跟踪张量的操作
反向传播:tenso.backward()执行反向传播,自动计算每个张量对损失函数的梯度
梯度:tensor.grad访问计算得到的梯度,最小化损失函数,优化模型
2 计算梯度
1.标量的梯度计算
import torch
def test01():
#标量的梯度计算
#创建标量,必须是浮点类型(涉及算术运算会有小数)
x=torch.tensor(5,requires_grad=True,dtype=torch.float32)
#损失函数
y=x**2+2*x-5
#反向传播,计算梯度
y.backward()#计算梯度:1.y函数对x求导函数;2.把x当前的值带入上一步的函数中求导数值
#读取梯度值
print(x.grad)#打印出x的导数值(梯度值)
#不能手动更新
#x=x+5
if __name__=='__main__':
test01()
2.向量的梯度计算
import torch
def test02():
#向量的梯度计算
#创建向量
x=torch.tensor([1,2,3],requires_grad=True,dtype=torch.float64)
#损失函数
y=x**2+2*x-5
print(y)
y=y.sum()#得到一个标量
#y=y.mean()
y.backward()#梯度计算(y必须是一个标量,才能用这个标量对x求导)
print(x.grad)
if __name__=='__main__':
test02()
3.多标量的梯度计算
import torch
def test03():
#多标量的梯度计算
x1=torch.tensor(1.,requires_grad=True)
x2=torch.tensor(2.,requires_grad=True)
y=x1**2+3*x2-5
y.backward()#梯度计算
print(x1.grad)
print(x2.grad)
if __name__=='__main__':
test03()
4.多向量的梯度计算
import torch
def test04():
#多向量的梯度计算
x1=torch.tensor([1,2,3],requires_grad=True,dtype=torch.float32)
x2=torch.tensor([2,2,1],requires_grad=True,dtype=torch.float32)

最低0.47元/天 解锁文章
527

被折叠的 条评论
为什么被折叠?



