PyTorch 实践:把理论变成代码#

还记得 深度学习核心数学基础 的理论和 上篇:练习峰 的架构吗?这些理论怎么变成可运行的代码? 本章用 PyTorch 全部实现出来——从张量操作到完整训练流程,真正从知道到做到。

本章概览

章节

内容

与前面章节的联系

引言:从理论到代码

PyTorch 的设计哲学与学习路径

为什么要用框架?

从 NumPy 到 PyTorch:张量的本质

从 NumPy 平滑过渡到 PyTorch

计算图 的实现

张量操作:数据在网络中的流动

张量操作详解

数据在计算图中如何流动

神经网络模块:搭建计算图

用 nn.Module 搭建网络

全连接:赤手空拳 和 卷积:发现装备 的代码实现

自动微分:PyTorch 的核心魔法

自动微分机制

反向传播算法 的 PyTorch 实现

优化器:用梯度更新参数

优化器与参数更新

梯度下降与优化算法 的多种变体

完整训练流程

完整训练流程

训练基础:登山纪律 的代码化

调试与可视化技巧

调试与可视化技巧

训练中的常见问题诊断

工程最佳实践

工程最佳实践

操控效率:效果、速度与硬件的三角权衡 中的效率优化

使用训练框架

使用训练框架

工程最佳实践 的工程化落地

学习路径

本章是前两章的实践延伸:

        graph LR
    A[数学基础<br/>理解原理] --> B[PyTorch 实践<br/>代码实现]
    C[神经网络<br/>知道建什么] --> B
    B --> D[你能独立搭建<br/>和训练神经网络]
    

核心认知:PyTorch 不是新技术,而是前两章理论的代码表达——每个 API 都有对应的数学概念。

前置知识

环境配置

pip install torch torchvision

如有 GPU:

pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118

验证:

import torch
print(torch.__version__)
print(torch.cuda.is_available())

贡献者与修订历史

查看详细修订记录
  • dc35df2 2026-06-14 - Heyan Zhu: refactor: unify into two-chapter mountain-climbing narrative
  • f1c39fd 2026-05-11 - Heyan Zhu: docs: deduplicate index & introduction; fix the latex export problem on index content structures
  • 2dc78ed 2026-05-09 - Heyan Zhu: fix: address latex errors when building pdf
  • f159d56 2026-05-08 - Heyan Zhu: fix: address complaints from the linter
  • b55c384 2026-05-01 - Heyan Zhu: docs: fix document cross-references and add anchor tags
  • 0cdb1e4 2026-04-29 - Heyan Zhu: feat: add model-serving chapter and update related content
  • b20ef3e 2026-04-28 - Heyan Zhu: docs: update pytorch practice section with detailed explanations and code examples
  • dcecce4 2026-01-26 - Heyan Zhu: docs: enrich math fundamentals documentation with code captions and TikZ visualizations
  • 0c291d7 2025-12-10 - Heyan Zhu: docs: restructure course materials and add new content