🧠 1. 安装与基础

# 安装 CPU 版本
pip install torch torchvision torchaudio

# 安装 GPU 版本(CUDA 12.1 示例)
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
import torch
print(torch.__version__)    # 版本
print(torch.cuda.is_available())  # 检查 GPU

📦 2. 张量(Tensor)基础

# 创建张量
x = torch.tensor([1, 2, 3])          # 从列表
x = torch.zeros(3, 3)                # 全零
x = torch.ones(2, 2)                  # 全一
x = torch.eye(3)                      # 单位矩阵
x = torch.rand(2, 3)                  # 均匀分布
x = torch.randn(2, 3)                 # 正态分布
x = torch.arange(0, 10, 2)            # 等差数列
x = torch.linspace(0, 1, steps=5)     # 等间隔数列

# 张量属性
print(x.shape, x.dtype, x.device)

# 数据类型
x = x.float()  # 转 float32
x = x.double() # 转 float64
x = x.int()    # 转 int32

# 张量运算
y = torch.tensor([4, 5, 6])
print(x + y)       # 加法
print(x * y)       # 逐元素乘
print(torch.dot(x, y))  # 点积
print(x @ y)       # 矩阵乘

🔄 3. 设备(CPU/GPU)操作

# 放到 GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = x.to(device)

# 直接创建在 GPU
x = torch.rand(2, 2, device="cuda")

🧮 4. 自动求导(Autograd)

# 自动求导
x = torch.tensor(2.0, requires_grad=True)
y = x ** 2 + 3 * x + 1
y.backward()  # dy/dx
print(x.grad)  # 输出梯度:7

🏗 5. 神经网络构建(torch.nn)

import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(10, 50)
        self.fc2 = nn.Linear(50, 1)

    def forward(self, x):
        x = F.relu(self.fc1(x))
        return self.fc2(x)

model = Net()
print(model)

⚡ 6. 损失函数 & 优化器

import torch.optim as optim

criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)

🔁 7. 训练循环模板

for epoch in range(epochs):
    for data, target in dataloader:
        optimizer.zero_grad()      # 清空梯度
        output = model(data)       # 前向传播
        loss = criterion(output, target) # 计算损失
        loss.backward()            # 反向传播
        optimizer.step()           # 更新参数

🔍 8. 推理(评估模式)

model.eval()
with torch.no_grad():  # 禁用梯度
    pred = model(x)

📊 9. 数据加载(DataLoader)

from torch.utils.data import DataLoader, TensorDataset

dataset = TensorDataset(torch.randn(100, 10), torch.randn(100, 1))
loader = DataLoader(dataset, batch_size=16, shuffle=True)

🏎 10. 常用加速技巧

  • with torch.no_grad():推理时禁用梯度
  • model.eval():关闭 Dropout / BatchNorm
  • 使用 GPU:model.to("cuda")
  • 使用 AMP(自动混合精度):torch.cuda.amp

微信扫一扫

作者:mospan
微信关注:墨斯潘園
本文出处:http://mospany.github.io/2025/08/09/pytorch-data-sheet/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。