基本数学运算
加减乘除
import torch
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
# 加法
print(a + b) # tensor([5, 7, 9])
print(torch.add(a, b)) # tensor([5, 7, 9])
# 减法
print(a - b) # tensor([-3, -3, -3])
# 乘法(元素级)
print(a * b) # tensor([4, 10, 18])
# 除法
print(b / a) # tensor([4.0, 2.5, 2.0])
矩阵乘法
a = torch.tensor([[1, 2], [3, 4]])
b = torch.tensor([[5, 6], [7, 8]])
# 矩阵乘法
result = torch.matmul(a, b)
# 或者
result = a @ b
print(result)
# tensor([[19, 22],
# [43, 50]])
张量变形
# 原始张量
x = torch.arange(12)
print(x) # tensor([0, 1, 2, ..., 11])
# reshape - 改变形状
x1 = x.reshape(3, 4)
print(x1.shape) # torch.Size([3, 4])
# view - 改变形状(需要连续内存)
x2 = x.view(4, 3)
print(x2.shape) # torch.Size([4, 3])
# transpose - 转置
x3 = x1.transpose(0, 1)
print(x3.shape) # torch.Size([4, 3])
# squeeze - 删除维度为1的维度
x4 = torch.randn(1, 3, 1, 4)
x5 = x4.squeeze()
print(x5.shape) # torch.Size([3, 4])
# unsqueeze - 增加维度
x6 = torch.randn(3, 4)
x7 = x6.unsqueeze(0) # 在第0维增加
print(x7.shape) # torch.Size([1, 3, 4])
张量索引与切片
tensor = torch.arange(12).reshape(3, 4)
print(tensor)
# tensor([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]])
# 索引
print(tensor[0, 1]) # tensor(1)
# 切片
print(tensor[1:, :2]) # 第1行之后,前2列
# tensor([[4, 5],
# [8, 9]])
# 高级索引
indices = torch.tensor([0, 2])
print(tensor[indices]) # 第0行和第2行
# tensor([[ 0, 1, 2, 3],
# [ 8, 9, 10, 11]])
张量拼接与分割
# 拼接
a = torch.tensor([[1, 2], [3, 4]])
b = torch.tensor([[5, 6], [7, 8]])
# 按行拼接
result = torch.cat([a, b], dim=0)
print(result.shape) # torch.Size([4, 2])
# 按列拼接
result = torch.cat([a, b], dim=1)
print(result.shape) # torch.Size([2, 4])
# 堆叠(创建新维度)
result = torch.stack([a, b], dim=0)
print(result.shape) # torch.Size([2, 2, 2])
# 分割
tensor = torch.arange(12).reshape(4, 3)
chunks = torch.chunk(tensor, 2, dim=0) # 分成2块
print(len(chunks)) # 2