1. 创建tensor的方法
import torch
x = torch.empty(5, 3) # 创建未初始化的矩阵
x = torch.rand(5, 3) # 创建随机初始化矩阵
x = torch.zeros(5, 3, dtype=torch.long) # 创建 0 矩阵
x = torch.tensor([5.5, 3]) # 直接从数据构造张量
x = x.new_ones(5, 3, dtype=torch.double) # he returned Tensor has the same `torch.dtype` `torch.device` as this tensor.
x = torch.randn_like(x, dtype=torch.float) # 重载 dtype!
x.size() # 获取张量形状
2. 运算
y = torch.rand(5, 3) # 加法形式 1
print(torch.add(x, y)) # 加法形式 2
result = torch.empty(5, 3)
torch.add(x, y, out=result) # 加法形式 2+
y.add_(x) # 加法形式 3
x[:, 1] # 切片操作
x = torch.randn(4, 4)
y = x.view(16) # 改变形状
z = x.view(-1, 8) # -1 自动计算维度大小
x = torch.randn(1)
x.item() # item() 方法获取 python 数值
3. 与Numpy转换
a = torch.ones(5)
b = a.numpy() # tensor 转换为 numpy
a.add_(1) # a 改变,b 也会跟着变
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a) # numpy 转换为 pytorch
4. GPU加速
# 当GPU可用时,我们可以运行以下代码
# 我们将使用`torch.device`来将tensor移入和移出GPU
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA device object
y = torch.ones_like(x, device=device) # 直接在GPU上创建tensor
x = x.to(device) # 或者使用`.to("cuda")`方法
z = x + y
print(z)
print(z.to("cpu", torch.double)) # `.to`也能在移动时改变dtype