Skip to content

PyTorch 张量运算核心详解

张量是 PyTorch 的核心数据结构,所有计算都建立在张量运算之上。深入理解张量操作是高效使用 PyTorch 的基础。

张量运算

张量创建与属性

python
import torch

# 从数据创建
t = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32, device='cuda')

# 常用创建方式
zeros = torch.zeros(3, 4)
ones = torch.ones(2, 3)
randn = torch.randn(100, 50)  # 标准正态分布
arange = torch.arange(0, 10, step=2)

# 张量属性
print(t.shape)    # torch.Size([2, 2])
print(t.dtype)    # torch.float32
print(t.device)   # cuda:0
print(t.requires_grad)  # False

广播机制

python
# 广播规则:从最右维度开始,维度为1或相等时可广播
a = torch.randn(3, 1, 4)  # [3, 1, 4]
b = torch.randn(1, 5, 4)  # [1, 5, 4]
c = a + b                  # [3, 5, 4]

避免隐式广播错误

广播可能导致意外的维度扩展。建议使用 tensor.expand()tensor.unsqueeze() 显式操作,避免难以调试的维度问题。

相关资源

最近更新