1. 张量的创建
import torch
# 从Python列表/NumPy数组创建
torch.tensor([1, 2, 3])
torch.tensor(np.array([1, 2, 3]))
# 创建特殊值张量
torch.zeros(2, 3) # 全0张量
torch.ones(2, 3) # 全1张量
torch.eye(3) # 单位矩阵
torch.full((2, 3), 7) # 全为指定值的张量
# 创建序列张量
torch.arange(0, 10, 2) # 等差序列
torch.linspace(0, 1, 5) # 等距序列
# 创建随机张量
torch.rand(2, 3) # [0,1)均匀分布
torch.randn(2, 3) # 标准正态分布
torch.randint(0, 10, (2, 3)) # 随机整数
2. 张量的类型转换
# 数据类型转换
x = torch.tensor([1, 2], dtype=torch.int32)
x.float() # → torch.float32
x.double() # → torch.float64
x.long() # → torch.int64
x.bool() # → torch.bool
# 设备转换(CPU/GPU)
x.cuda() if torch.cuda.is_available() else x.cpu()
x.to('cuda' if torch.cuda.is_available() else 'cpu')
# 与NumPy互转
x.numpy()
torch.from_numpy(np.array([1, 2]))
3. 张量数值计算
a = torch.tensor([1.0, 2.0])
b = torch.tensor([3.0, 4.0])
# 基础算术运算(元素级)
a + b, a - b, a * b, a / b
a ** 2
# 矩阵乘法
a @ b
torch.matmul(a, b)
# 聚合运算
torch.sum(a)
torch.mean(a)
torch.max(a)
torch.min(a)
torch.argmax(a)
torch.argmin(a)
torch.std(a)
torch.var(a)
4. 张量运算函数
x = torch.tensor([-1.0, 2.0, -3.0])
# 数学函数
torch.abs(x)
torch.sqrt(torch.abs(x))
torch.exp(x)
torch.log(torch.abs(x) + 1e-6)
torch.sin(x), torch.cos(x), torch.tanh(x)
# 逻辑与比较函数
x > 0, x == 2
torch.gt(x, 0)
torch.eq(x, 2)
torch.where(x > 0, x, 0) # 条件选择
5. 张量索引操作
x = torch.rand(3, 4)
# 基本索引
x[0] # 取第0行
x[:, 0] # 取第0列
x[1:3, :] # 取1-2行
# 布尔索引
mask = x > 0.5
x[mask]
# 高级索引
torch.index_select(x, dim=0, index=torch.tensor([0, 2]))
torch.masked_select(x, mask)
torch.gather(x, dim=1, index=torch.tensor([[0], [2]]))
6. 张量形状操作
x = torch.rand(2, 3)
# 查看形状
x.shape
x.size()
# 改变形状
x.reshape(3, 2)
x.view(3, 2) # 要求内存连续
x.flatten() # 展平为1维
x.squeeze() # 移除大小为1的维度
x.unsqueeze(0) # 增加一个维度
# 维度交换
x.permute(1, 0) # 任意维度重排
x.transpose(0, 1) # 交换两个维度(转置)
7. 张量拼接操作
a = torch.rand(2, 3)
b = torch.rand(2, 3)
# 拼接(不增加新维度)
torch.cat([a, b], dim=0) # 按行拼接 → (4, 3)
torch.cat([a, b], dim=1) # 按列拼接 → (2, 6)
# 堆叠(增加新维度)
torch.stack([a, b], dim=0) # → (2, 2, 3)
torch.stack([a, b], dim=1) # → (2, 2, 3)
8. 自动微分模块
# 开启梯度追踪
x = torch.tensor(3.0, requires_grad=True)
y = x ** 2
# 反向传播计算梯度
y.backward()
print(x.grad) # dy/dx = 2x = 6
# 关闭梯度追踪
with torch.no_grad():
y = x ** 2 # 不记录计算图
# 梯度清零
x.grad.zero_()
9. 案例 - 线性回归(完整示例)
import torch
# 1. 准备数据
X = torch.rand(100, 1) * 10
y = 2 * X + 3 + torch.randn(100, 1) * 0.5
# 2. 定义参数
w = torch.randn(1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)
lr = 0.01
epochs = 1000
# 3. 训练循环
for epoch in range(epochs):
# 前向传播
y_pred = X @ w + b
loss = torch.mean((y_pred - y) ** 2)
# 反向传播
loss.backward()
# 参数更新(需关闭梯度)
with torch.no_grad():
w -= lr * w.grad
b -= lr * b.grad
# 梯度清零
w.grad.zero_()
b.grad.zero_()
if (epoch + 1) % 100 == 0:
print(f"Epoch {epoch+1}, Loss: {loss.item():.4f}")