PyTorch是一个python库,它主要提供了两个高级功能:
- GPU加速的张量计算
- 构建在反向自动求导系统上的深度神经网络
1. 定义数据
一般定义数据使用torch.Tensor , tensor的意思是张量,是数字各种形式的总称
简单理解张量:
0维张量:标量(一个数)
1维张量:向量(一维数组)
2维张量:矩阵(二维数组)
浅谈什么是张量
import torch # 可以是一个数 x = torch.tensor(666) print(x) #可以是一组一维向量 x=torch.tensor([1,2,3,4,5,6]) print(x) # 可以是二维数组(矩阵) # 2*3 全1矩阵 x = torch.ones(2,3) print(x) # 可以是任意维度的数组(张量) x = torch.ones(2,3,4) print(x) # 创建一个空张量 x = torch.empty(5,3) print(x) # 创建一个随机初始化的张量 x = torch.rand(5,3) print(x) # 创建一个全0的张量,里面的数据类型为 long x = torch.zeros(5,3,dtype=torch.long) print(x) # 基于现有的tensor,创建一个新tensor, # 从而可以利用原有的tensor的dtype,device,size之类的属性信息 y = x.new_ones(5,3) #tensor new_* 方法,利用原来tensor的dtype,device print(y) # 利用原来的tensor的大小,但是重新定义了 z = torch.randn_like(x, dtype=torch.float) print(z)2.定义操作
# 创建一个 2x4 的tensor
m = torch.Tensor([[2, 5, 3, 7],
[4, 2, 1, 9]])
print(m.size(0), m.size(1), m.size(), sep=' -- ')
# 返回 m 中元素的数量
print(m.numel())
# 返回 第0行,第2列的数
print(m[0][2])
# 返回 第1列的全部元素
print(m[:, 1])
# 返回 第0行的全部元素
print(m[0,:])
# Create tensor of numbers from 1 to 5
# 注意这里结果是1到4,没有5
v = torch.arange(1, 5)
print(v)
# Scalar product m与v的标量积
#expected scalar type Float but found Long
v = torch.arange(1, 5,dtype=torch.float)
m @ v
特别注意:计算标量积时数据类型需为float型
# Scalar product m与v的标量积 #expected scalar type Float but found Long v = torch.arange(1, 5,dtype=torch.float) m @ v
# Calculated by 1*2 + 2*5 + 3*3 + 4*7 m[[0], :] @ v # Add a random tensor of size 2x4 to m m + torch.rand(2, 4) # 转置,由 2x4 变为 4x2 print(m.t()) # 使用 transpose 也可以达到相同的效果,具体使用方法可以百度 print(m.transpose(0, 1)) # returns a 1D tensor of steps equally spaced points between start=3, end=8 and steps=20 torch.linspace(3, 8, 20)
from matplotlib import pyplot as plt # matlabplotlib 只能显示numpy类型的数据,下面展示了转换数据类型,然后显示 # 注意 randn 是生成均值为 0, 方差为 1 的随机数 # 下面是生成 1000 个随机数,并按照 100 个 bin 统计直方图 plt.hist(torch.randn(1000).numpy(), 100);
# 当数据非常非常多的时候,正态分布会体现的非常明显 plt.hist(torch.randn(10**6).numpy(), 100);
# 创建两个 1x4 的tensor a = torch.Tensor([[1, 2, 3, 4]]) b = torch.Tensor([[5, 6, 7, 8]]) # 在 0 方向拼接 (即在 Y 方各上拼接), 会得到 2x4 的矩阵 print( torch.cat((a,b), 0)) # 在 1 方向拼接 (即在 X 方各上拼接), 会得到 1x8 的矩阵 print( torch.cat((a,b), 1))



