张量的理解
在 PyTorch 中,torch.tensor()
是创建张量的核心接口,这里的张量(Tensor)本质上是多维数组,与 NumPy 的 ndarray
类似,但增加了自动微分、GPU 加速和分布式计算等深度学习特有的功能。以下从四个维度解析 PyTorch 张量:
一、张量的基础概念:多维数组 + 计算图
1. 数据结构
PyTorch 张量是多维数组,支持任意维度:
- 0 维张量(标量):
tensor(3.14)
- 1 维张量(向量):
tensor([1, 2, 3])
- 2 维张量(矩阵):
tensor([[1, 2], [3, 4]])
- 更高维度:如图片张量
[batch, channels, height, width]
2. 与 NumPy 的关系
- 相似性:底层数据结构均为多维数组,支持切片、索引、广播等操作。
- 差异性:PyTorch 张量可在 GPU 上运算,且支持自动微分(通过
requires_grad=True
启用)。
3. 核心属性
x = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32, device="cuda")
print(x.shape) # 形状:(2, 2)
print(x.dtype) # 数据类型:torch.float32
print(x.device) # 存储设备:cuda:0(若有 GPU)
print(x.requires_grad) # 是否跟踪梯度:False(默认)
二、创建张量的常见方式
1. 直接从数据创建
torch.tensor([1, 2, 3]) # 从列表创建
torch.tensor(np.array([1, 2, 3])) # 从 NumPy 数组创建
2. 初始化特殊张量
torch.zeros(3, 4) # 全零张量
torch.ones(2, 2) # 全一张量
torch.eye(3) # 单位矩阵
torch.rand(2, 3) # 均匀分布随机数 [0, 1)
torch.randn(2, 3) # 标准正态分布随机数
3. 从已有张量创建
x = torch.tensor([1, 2])
x.new_ones(3, 3) # 与 x 同 dtype 和 device 的全一张量
torch.zeros_like(x) # 与 x 同形状的全零张量
三、张量的核心操作
1. 数学运算
x = torch.tensor([1, 2])
y = torch.tensor([3, 4])# 逐元素运算
print(x + y) # 加法:tensor([4, 6])
print(x * y) # 乘法:tensor([3, 8])
print(torch.exp(x)) # 指数运算# 矩阵运算
print(x @ y) # 点积:tensor(11)
print(torch.matmul(x, y)) # 矩阵乘法
2. 形状操作
x = torch.rand(2, 3, 4)
print(x.shape) # torch.Size([2, 3, 4])
print(x.reshape(2, 12)) # 重塑为 2×12 张量
print(x.permute(1, 0, 2)) # 交换维度:(3, 2, 4)
print(x.unsqueeze(1)) # 在第1维插入维度:(2, 1, 3, 4)
3. 索引与切片
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(x[0]) # 第一行:tensor([1, 2, 3])
print(x[:, 1]) # 第二列:tensor([2, 5])
print(x[x > 3]) # 条件索引:tensor([4, 5, 6])
4. GPU 加速
# 将张量移至 GPU
if torch.cuda.is_available():x = x.to("cuda")
四、深度学习核心:自动微分
PyTorch 张量通过 requires_grad=True
开启自动求导功能,构建计算图:
# 定义可求导张量
x = torch.tensor([2.0], requires_grad=True)
y = x**2 + 3*x# 反向传播计算梯度
y.backward()
print(x.grad) # 梯度 dy/dx = 2x + 3 = 7
应用场景:优化模型参数
import torch.optim as optim# 定义简单模型
w = torch.tensor([0.5], requires_grad=True)
optimizer = optim.SGD([w], lr=0.01)# 优化循环
for _ in range(100):loss = (w * 3 - 12)**2 # 目标:w → 4loss.backward()optimizer.step()optimizer.zero_grad()print(w.item()) # 接近 4.0
五、张量与深度学习的结合
1. 数据表示
- 图像:
[batch_size, 3, height, width]
- 文本:
[seq_len, batch_size, embedding_dim]
- 音频:
[batch_size, channels, time_steps]
2. 模型构建
神经网络的每一层本质上是张量运算:
import torch.nn as nnmodel = nn.Sequential(nn.Linear(10, 20), # 输入 10 维 → 输出 20 维nn.ReLU(),nn.Linear(20, 1) # 输出 1 维
)output = model(torch.rand(5, 10)) # 输入 5×10 张量
print(output.shape) # torch.Size([5, 1])
六、总结:PyTorch 张量的核心价值
- 统一数据结构:用张量表示所有数据(图像、文本、音频),简化开发流程。
- 硬件加速:无缝支持 GPU 和 TPU,提升计算效率。
- 自动微分:无需手动推导梯度,大幅降低实现复杂度。
- 分布式训练:支持多机多卡并行计算,扩展训练规模。