PyTorch深度学习教程

通俗易懂的交互式PyTorch学习指南

1. PyTorch简介 +

什么是PyTorch

PyTorch是由Meta(Facebook)开发的深度学习框架,具有以下特点:

安装PyTorch

# CPU版本 pip install torch torchvision torchaudio # CUDA版本(根据CUDA版本选择) pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
点击"运行命令"查看安装说明

2. 张量(Tensors)基础 +

创建张量

import torch # 从列表创建 data = [[1, 2], [3, 4]] x = torch.tensor(data) print(x) # 特殊张量 zeros = torch.zeros(2, 3) # 全0张量 ones = torch.ones(2, 3) # 全1张量 rand = torch.rand(2, 3) # 随机张量 # 指定设备 device = "cuda" if torch.cuda.is_available() else "cpu" x = torch.tensor([1, 2, 3], device=device)
点击"运行代码"查看结果

张量操作

# 基本运算 x = torch.tensor([1, 2, 3]) y = torch.tensor([4, 5, 6]) add = x + y # 加法 sub = x - y # 减法 mul = x * y # 乘法 div = x / y # 除法 # 矩阵乘法 A = torch.rand(3, 4) B = torch.rand(4, 5) C = torch.matmul(A, B) # 或 A @ B
点击"运行代码"查看结果

3. 自动微分(Autograd) +

梯度计算

# 需要梯度的张量 x = torch.tensor(2.0, requires_grad=True) y = x ** 2 + 3 * x + 1 # 计算梯度 y.backward() print(x.grad) # dy/dx = 2x + 3 = 7
点击"运行代码"查看结果

复杂梯度计算

x = torch.tensor([1.0, 2.0], requires_grad=True) y = torch.sum(x ** 2) # y = x1² + x2² y.backward() print(x.grad) # [2.0, 4.0]
点击"运行代码"查看结果

4. 神经网络模块(nn.Module) +

定义神经网络

import torch.nn as nn class SimpleNet(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(10, 50) # 输入10维,输出50维 self.relu = nn.ReLU() self.fc2 = nn.Linear(50, 1) # 输出1维 def forward(self, x): x = self.fc1(x) x = self.relu(x) x = self.fc2(x) return x # 创建模型 model = SimpleNet() print(model)
点击"运行代码"查看结果

常用层类型

# 线性层 linear = nn.Linear(in_features=10, out_features=5) # 卷积层 conv = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3) # 循环层 lstm = nn.LSTM(input_size=10, hidden_size=20, num_layers=2) # 激活函数 relu = nn.ReLU() sigmoid = nn.Sigmoid() tanh = nn.Tanh()
点击"运行代码"查看结果

5. 损失函数和优化器 +

损失函数

import torch.nn.functional as F # 均方误差 loss_fn = nn.MSELoss() # 交叉熵损失(分类问题) loss_fn = nn.CrossEntropyLoss() # 二元交叉熵 loss_fn = nn.BCELoss()
点击"运行代码"查看结果

优化器

import torch.optim as optim # 随机梯度下降 optimizer = optim.SGD(model.parameters(), lr=0.01) # Adam优化器(推荐) optimizer = optim.Adam(model.parameters(), lr=0.001) # 带动量的SGD optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
点击"运行代码"查看结果

© 2025 AI框架教程 - 专为初学者设计的深度学习教程

武哥出品

返回主页