torch教程

Pytorch是一个机遇Torch的python第三方库,是当前最流行的机器学习库之一。本文基于Pytorch官方中文教程。

Tensor(张量)

tensor类似于numpy中的adarray,是n维张量。

创建tensor

#张量:不初始化(都是0)
print("构造张量:不初始化")
x = torch.empty((5,3))
print(x)

#随机初始化
print("构造张量:随机初始化")
x = torch.rand((5,3))
print(x)

#全0矩阵
print("构造张量:全0")
x = torch.zeros((5,3), dtype=torch.long)
print(x)

#从列表构造张量
print("构造张量:从列表构造张量")
x = torch.tensor([1, 2, 3])
print(x)

#从已有张量构造张量:y会继承x的属性
print("构造张量:从已有张量构造张量")
y = x.new_ones((5, 3), dtype=torch.long)
print(y)
y = torch.rand_like(x, dtype=torch.float)
print(y)

在这里插入图片描述

基本属性

#获取维度信息
print("获取维度信息")
x = torch.empty((5,3))
print(x.shape)

#基本运算
print("基本运算")
x = torch.rand((5,3))
y = torch.rand_like(x)
print(x+y)
print(x.add(y))

#带有_的函数会改变调用此函数的对象
x.add_(y)
print(x)

#改变形状
print("改变形状")
x = torch.rand(4,4)
y = x.view(-1, 8)
print(x.size(), y.size())

#如果只有一个元素,获取元素
print("获取元素")
x = torch.rand((1,1))
print(x)
print(x.item())

在这里插入图片描述

自动微分

tensor最大的特点是可以自动微分

#%%
#自动微分
import torch
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()
#out是标量,因此反向传播无需指定参数
out.backward()
#打印梯度
print("打印梯度")
print(x.grad)

#雅克比向量积
print("雅克比向量积")
x = torch.rand(3, requires_grad=True)
y = x * 2
print(y)
#反向传播的参数是权重
#I = w1*y1 + w2*y2 + w3 * y3
#这里是I对x的各个分量求导
w = torch.tensor([1,2,3], dtype=torch.float)
y.backward(w)
print(x.grad)

在这里插入图片描述

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值