Pytorch基础
PyTorch入门
Tensors(张量)
Tensors类似于Numpy的ndarrays,同时Tensors可以使用GPU进行计算。
import torch
构造一个5×3的矩阵,不初始化。
x = torch.empty(5, 3)
print(x)
构造一个随机初始化的矩阵。
x = torch.rand(5, 3)
print(x)
构造一个数据类型为long的全0矩阵。
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
构造一个张量,直接使用数据:
x = torch.tensor([5, 3])
print(x)
tensor.rand
:创建一组均匀分布的随机数
tensor.randn
:创建一组正态分布的随机数
tensor.ones
:创建一组全为1的数组
tensor.zeros
:创建一组全为0的数组
基于一个已经存在的tensor创建tensor。
x = torch.randn_like(x, dtype=torch.float)
print(x)
# 获取维度信息
print(x.size())
操作
加法:
方法一:不改变x,y
x = torch.ones(2, 2)
y = torch.ones(2, 2)
print(x + y)
print(x, y)
方法二:不改变x,y,可提供一个输出
x = torch.ones(2, 2)
y = torch.ones(2, 2)
result = torch.empty(2, 2)
print(torch.add(x, y, out=result))
print(x)
print(y)
print(result)
方法三:改变x,y
x = torch.ones(5, 3)
y = torch.ones(5, 3)
y.add_(x)
print(x)
print(y)
任何使张量会发生变化的操作都有一个前缀’_’。
乘法
- 元素相乘
tensor.mul
,torch.mul()
x1 = torch.tensor([[2, 2], [2, 2]])
x2 = torch.tensor([[1, 2], [3, 4]])
print(torch.mul(x1, x2))
print(x1.mul(x2))
print(x1*x2)
- 矩阵相乘
torch.matmul()
,tensor @ tensor
x1 = torch.tensor([[2, 2], [2, 2]])
x2 = torch.tensor([[1, 2], [3, 4]])
print(torch.matmul(x1, x2))
print(x1 @ x2)
索引
可以使用Numpy类似的索引操作。
x = torch.rand(3,2)
print(x)
print(x[:, 1])
调整大小
可以使用 torch.view
改变一个tensor的大小。
x = torch.randn(3, 2)
print(x)
y = x.view(6)
print(y)
取值
使用.item
可以获得tensor的value
x = torch.randn(1)
print(x)
print(x.item())
属性
形状、数据类型、tensor位置
tensor.shape
:Shape of tensor.
tensor.dtype
:Datatype of tensor.
tensor.device
:Device tensor is stored on.
GPU
把tensor
放到GPU上。
tensor = x
if torch.cuda.is_available():
tensor = tensor.to('cuda')
print(tensor.device)
连接
torch.cat
:沿着指定的维度连接tensor,增加现有维度的值 tensor的size必须相同
torch.stack
:增加一个维度
a = torch.tensor([[1, 2]