Pytorch是一个基于Python的科学计算库,类似于Numpy,但它可以使用GPU运算,也可以用它定义深度学习模型,并训练。本文介绍Pytorch基本数据类型Tensor,Tensor类似于Numpy的ndarray,可以在GPU上进行加速运算。
代码示例
1、创建tensor
import torch import numpy as np # 创建一个5行3列的未初始化矩阵 torch.empty(5, 3) # 初始化一个5x3的矩阵 torch.rand(5, 3) # 随机均匀分布,范围0-1 torch.randn(5, 3) # 随机正态分布,均值为0,方差为1 torch.zeros(5, 3) # 全0 torch.ones(5, 3) # 全1 # 根据列表创建 data = [[1, 2], [3, 4]] torch.tensor(data) # tensor([[1, 2],[3, 4]]) # 从numpy转化 np_data = np.array([1, 2, 3]) x = torch.tensor(np_data) # tensor([1, 2, 3]) # 创建相同形状的tensor torch.rand_like(x, dtype=torch.float) torch.ones_like(x) torch.zeros_like(x)
2、查看tensor属性
t = torch.randn(4, 3) t.shape # torch.Size([4, 3]) t.size() # torch.Size([4, 3]) t.dtype # torch.float32
3、tensor操作
t = torch.ones(3, 4) # 切片 print(t[:, 0]) # 第一列 print(t[..., -1]) # 最后一列 # 修改数值 t[1, 1] = 0 # reshape print(t.view(2, 6)) print(t.view(2, -1))
4、tensor运算
# 加法 t1 = torch.rand(3, 2) t2 = torch.ones(3, 2) print(t1 + t2) print(t1 + 1) t3 = torch.empty(3, 2) torch.add(t1, t2, out=t3) print(t3) # inplace=True t1.add_(t2) print(t1) t5 = torch.rand(2, 3) t6 = torch.rand(2, 3) # 矩阵乘法,一行乘一列 print(t5 @ t6.T) # 2x3 @ 3x2 print(torch.matmul(t5, t6.T)) # 对应元素相乘 print(t5 * t6) print(torch.mul(t5, t6).sum()) # 内积
5、其他
# 转numpy
t7 = torch.tensor([[1, 2], [3, 4]])
print(t7.numpy())
# 线性等距数列,且需要计算梯度
t8 = torch.linspace(1, 10, 20, requires_grad=True)
print(t8.data) # 不希望被autograd记录
# 取数值(脱壳)
t9 = torch.rand(1)
print(t9.item())
# 拼接
t10 = torch.ones(2, 3)
print(torch.cat([t10, t10], dim=1))
# GPU加速
device = 'cuda' if torch.cuda.is_available() else 'cpu'
t11 = torch.ones(3, device=device)
# 转numpy
print(t11.to('cpu').numpy())
print(t11.cpu().numpy())
参考文档:https://pytorch.org/tutorials/beginner/basics/tensorqs_tutorial.html
本文为 陈华 原创,欢迎转载,但请注明出处:http://www.chenhuax.com/read/306