什么是 PyTorch 张量?
PyTorch 中的张量(Tensor)是一个可以在 GPU 或 CPU 上进行高效计算的多维数组,类似于 NumPy 的 ndarray,但支持自动求导和 GPU 加速。
import torch
# 创建一个 2x3 的张量
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(x)
常用张量创建方法
# 从列表创建
torch.tensor([[1, 2], [3, 4]])
# 创建全0、全1张量
torch.zeros(2, 3)
torch.ones(2, 3)
# 创建随机数张量
torch.randn(2, 3) # 正态分布
torch.rand(2, 3) # 均匀分布
torch.randint(0, 10, (2, 3)) # 范围整数
torch.full((2, 3), 7) # 全填7
张量属性
x = torch.randn(2, 3)
x.shape # torch.Size([2, 3])
x.dtype # 数据类型(如 torch.float32)
x.device # 所在设备(如 'cuda:0' 或 'cpu')
张量操作
a = torch.tensor([1, 2])
b = torch.tensor([3, 4])
a + b # 加法
torch.dot(a, b) # 点乘
A = torch.randn(2, 3)
B = torch.randn(3, 4)
torch.matmul(A, B) # 矩阵乘法
A.T # 转置
A.view(6) # 改变形状
A.view(-1, 2) # 自动推导维度
GPU 加速
# 检查 GPU 是否可用
torch.cuda.is_available()
# 转移到 GPU
x = x.to("cuda")
# 回到 CPU
x = x.to("cpu")
自动求导
x = torch.tensor([2.0, 3.0], requires_grad=True)
y = x ** 2 + 2 * x
z = y.sum()
z.backward() # 自动反向传播
print(x.grad) # 输出梯度
NumPy 互操作
# Tensor 转 NumPy
x.numpy()
# NumPy 转 Tensor
import numpy as np
torch.from_numpy(np.array([1, 2, 3]))