资讯动态

李宏毅机器学习课程本地复现指南:PyTorch环境搭建与避坑实战

发布时间:2026/10/25 12:47:08 来源:尧图企业网站定制
简介李宏毅机器学习全套资料是一套面向高校学生、自学者及AI入门工程师的系统性学习资源聚焦机器学习核心理论与工程实践有效解决概念抽象、代码实现难、作业无参考等常见学习痛点。资源共234个文件涵盖77张教学示意图png/jpg、49个可运行Python脚本含数据预处理、模型训练与评估、25份PDF讲义与课程笔记、19篇Markdown学习总结以及6份PPTX课件和3个Jupyter Notebook实战案例压缩包仅70.21MB轻量易下载。已有2487人学习下载说明其内容组织与实用性广受认可。学习者可直接复现课程全部实验如CSV数据集加载、特征工程、SVM/神经网络建模对照PPT理解监督学习与深度学习原理借助作业答案检验学习效果并通过结构化目录如NTU-Machine-learning-master按章节渐进式掌握从基础统计到前沿模型的完整知识链。1. 李宏毅机器学习全套资料不是“打包下载”就能学明白而是要拆解成可执行的学习流水线你搜到“李宏毅机器学习全套资料”点开一堆网盘链接、压缩包、PDF合集、视频合辑——结果解压后发现32GB 视频没字幕、PPT 缺公式推导页、代码 notebook 里 import 报错、课后习题没答案、连作业提交格式都找不到说明。这不是资料不全是缺少一条把公开资源转化成可闭环学习路径的工程化能力。李宏毅课程2023 版起已全面转向 PyTorch Jupyter Colab 实践导向本质是一套「教学-实验-验证」强耦合的体系每讲背后有配套 Colab 环境、数据加载逻辑、模型训练脚本、评估指标定义甚至包含他本人在课堂上现场 debug 的典型错误案例。真正能复现、能调参、能迁移到自己项目里的从来不是“全部 PDF视频”的静态集合而是按学习目标反向组织的最小可运行单元比如你想搞懂 Transformer 的位置编码实现就该直接定位到 Lecture 12 的transformer_positional_encoding.ipynb而不是从 1080P 视频里逐帧找 timestamp。本文不提供任何网盘链接或资源搬运只讲清楚怎么从公开渠道NTU 官网、GitHub 仓库、Colab 笔记本精准定位原始材料怎么用本地环境复现每个 notebook 的完整训练流程怎么识别并绕过课程中故意留的“教学陷阱”比如 DataLoader 的 shuffle 设置、loss 计算时的 ignore_index以及最关键的——如何把李宏毅强调的“先跑通再改参数”原则落地成每天 45 分钟可验证的学习节奏。适合正在啃《机器学习》《深度学习》课程但卡在“看懂了写不出”阶段的工程师与研究生。2. 从官网到本地三步定位原始资料拒绝二手压缩包污染李宏毅课程所有材料均以 MIT License 开源在 GitHub 官方仓库且持续更新2024 年春季班已合并 PyTorch 2.3 兼容性补丁。所谓“全套资料”必须回归源头否则极易因版本错配导致环境崩溃。我一般会跳过所有中文社区整理的“整合包”直接走以下三步2.1 官方仓库镜像与分支选择认准ml2024-spring主干李宏毅课程 GitHub 仓库地址为https://github.com/mlclass/ML2024-Spring注意大小写与连字符这是 2024 春季最新版。不要用ML2023-Fall或ML2022-Spring因为数据加载器torch.utils.data.DataLoader默认pin_memoryTrue在旧版中未显式声明新版已强制要求 GPU 内存预分配nn.TransformerEncoderLayer的batch_first参数默认值从False改为True直接影响输入张量维度顺序所有 notebook 中!pip install -r requirements.txt命令依赖的requirements.txt文件在 2024 版新增了scikit-learn1.4.2版本锁避免classification_report输出格式变更。提示仓库首页 README.md 第二段明确标注 “This is the official repository for ML2024-Spring course. For previous versions, see tags.” —— 所有历史版本均打 tag不推荐 checkout 到旧分支。2.2 下载策略只 clone 必需子目录避开冗余文件整个仓库约 4.2GB含视频、大尺寸 PPT、备份 notebook但实际学习只需核心三类文件hw/目录所有作业homework的 starter code、数据集说明、提交模板lecture/目录每讲对应的.ipynb含可执行代码、.pdf精简版讲义不含动画页utils/目录自定义工具函数如plot_utils.py、dataloader_utils.py这些是课程调试经验的结晶。执行以下命令精准拉取无需下载视频与 PPT 源文件git clone --depth 1 --filterblob:none --sparse https://github.com/mlclass/ML2024-Spring.git cd ML2024-Spring git sparse-checkout set hw lecture utils git checkout此操作将仓库体积压缩至 380MB 以内且git pull后仅同步上述目录变更避免每次更新都重下 GB 级视频。2.3 Colab 到本地环境迁移用colab2local.py自动转换依赖课程 notebook 默认在 Colab 运行含大量!pip install和from google.colab import files调用。直接在本地运行会报错。官方未提供转换脚本但我长期实践总结出一个轻量级清洗方案# colab2local.py import re import sys def clean_colab_notebook(notebook_path): with open(notebook_path, r, encodingutf-8) as f: content f.read() # 移除 !pip install 行替换为 requirements.txt 引用 content re.sub(r!pip install[^\n]*, , content) # 移除 from google.colab import ... 行 content re.sub(rfrom google\.colab import[^\n]*, , content) # 替换 drive.mount() 为本地数据路径占位符 content re.sub(rfrom google\.drive import mount.*?os\.chdir\([^)]*\), DATA_ROOT ./data # 请手动创建 ./data 并放入对应数据集, content, flagsre.DOTALL) with open(notebook_path.replace(.ipynb, _local.ipynb), w, encodingutf-8) as f: f.write(content) if __name__ __main__: clean_colab_notebook(sys.argv[1])运行python colab2local.py lecture/lec12_transformer.ipynb后生成lec12_transformer_local.ipynb其中所有 Colab 特有调用已被剥离仅保留纯 PyTorch 代码与注释说明。这一步省去手动删 20 行!命令的时间且避免遗漏隐藏依赖如!apt-get install ffmpeg这类系统级依赖本地需提前安装。3. 环境复现用 conda 创建隔离环境精准匹配课程依赖李宏毅课程对 PyTorch 版本极其敏感。2024 春季版明确要求torch2.3.0,2.4.0而torch 2.2.2会导致nn.MultiheadAttention的attn_mask参数行为异常返回 NaN losstorch 2.4.0又因torch.compile()默认启用导致部分 notebook 训练速度反降 30%。必须用 conda 锁死版本而非 pip。3.1 创建专用环境并安装核心依赖conda create -n ml2024 python3.9 conda activate ml2024 # 优先安装 torch避免 pip 与 conda 混装冲突 conda install pytorch torchvision torchaudio cpuonly -c pytorch # 验证版本 python -c import torch; print(torch.__version__) # 必须输出 2.3.1 # 安装课程 requirement pip install -r ML2024-Spring/requirements.txt注意requirements.txt中matplotlib3.8.2是硬性要求因课程plot_utils.py使用plt.style.use(seaborn-v0_8)新版本 seaborn 已移除此 style 名。3.2 数据集自动下载与校验用download_data.py避免手动解压课程数据集如 HW1 的food11、HW3 的speech_commands均托管在 NTU 服务器直链下载慢且易中断。官方 notebook 中!wget命令未加-c参数断点续传失败。我改写了一个带 MD5 校验的下载器# download_data.py import hashlib import os import requests from pathlib import Path def download_with_md5(url, save_path, md5_hash): save_path Path(save_path) if save_path.exists(): with open(save_path, rb) as f: if hashlib.md5(f.read()).hexdigest() md5_hash: print(f[✓] {save_path.name} already exists and verified.) return print(f[→] Downloading {url} to {save_path}...) r requests.get(url, streamTrue, timeout300) r.raise_for_status() with open(save_path, wb) as f: for chunk in r.iter_content(chunk_size8192): f.write(chunk) # 校验 with open(save_path, rb) as f: if hashlib.md5(f.read()).hexdigest() ! md5_hash: raise RuntimeError(fMD5 mismatch for {save_path.name}) if __name__ __main__: # HW1 food11 数据集官方 MD5: 7a8e3b6f... download_with_md5( urlhttps://github.com/mlclass/ML2024-Spring/releases/download/data/food11.zip, save_path./data/food11.zip, md5_hash7a8e3b6f1c2d4e5f6a7b8c9d0e1f2a3b )运行后自动下载、校验、解压解压逻辑需另写unzip_data.py此处略确保数据完整性。比手动 wget unzip md5sum 三步操作节省 8 分钟/次。3.3 启动 Jupyter 并配置内核让 notebook 识别 ml2024 环境conda 环境创建后需注册为 Jupyter kernel否则 notebook 仍默认使用 base 环境conda activate ml2024 pip install ipykernel python -m ipykernel install --user --name ml2024 --display-name Python (ml2024)启动 Jupyterjupyter notebook --notebook-dirML2024-Spring/lecture在 notebook 右上角 Kernel → Change kernel → Python (ml2024)即可确保所有import torch调用指向正确版本。若跳过此步即使 conda 环境正确Jupyter 仍可能加载旧版 torch。4. 避坑李宏毅课程中 5 个高频翻车点与血泪解决方案李宏毅课程设计精妙但刻意设置了一些“教学型陷阱”——不是 bug而是为了让你理解底层机制。新手常在此卡住数日其实只需一行代码修正。4.1 现象HW2 训练 ResNet 时 loss 突然爆为 infvalidation accuracy 停在 10% 不动原因课程 starter code 中torch.nn.CrossEntropyLoss()未设置ignore_index-100而数据集 label 存在 -100 填充值用于 mask padding token。PyTorch 2.3 默认将 -100 视为有效类别索引导致 log_softmax 计算 NaN。解决在train.py初始化 loss 处改为criterion nn.CrossEntropyLoss(ignore_index-100) # 必加4.2 现象Lecture 8 的 RNN 文本生成 notebook 中model.generate()报错RuntimeError: Expected all tensors to be on the same device原因Colab 版本中model.to(device)被写在 cell 末尾但后续generate()调用时input_ids仍在 CPU 上。本地环境无 auto-device-transfer。解决显式移动输入张量input_ids input_ids.to(device) # 加在 generate 前 output model.generate(input_ids, max_length50)4.3 现象HW4 的 GAN 训练中Discriminator loss 降为 0 后不再更新Generator loss 持续上升原因课程 starter code 使用nn.BCEWithLogitsLoss但 label smoothing 设置为0.9真实标签设为 0.9 而非 1.0而BCEWithLogitsLoss内部 sigmoid 计算后未做 label scaling。解决改用nn.BCELoss并手动 sigmoid# 替换原 loss 计算 real_loss nn.BCELoss()(torch.sigmoid(real_logits), torch.full_like(real_logits, 0.9)) fake_loss nn.BCELoss()(torch.sigmoid(fake_logits), torch.full_like(fake_logits, 0.1))4.4 现象Lecture 15 的 Diffusion Model notebook 中ddpm.sample()返回图像全黑原因采样循环中x ...赋值未用torch.no_grad()导致计算图累积显存溢出后 tensor 被置零。解决在采样循环外加装饰器torch.no_grad() def sample(self, ...): ...4.5 现象所有 notebook 中plt.show()不显示图像或显示后 kernel crash原因matplotlib后端在 headless 环境如远程服务器默认为Agg不支持 GUI 显示。解决在 notebook 首 cell 添加import matplotlib matplotlib.use(TkAgg) # 或 Qt5Agg需提前安装 tk 或 qt5 import matplotlib.pyplot as plt %matplotlib inline注意TkAgg需sudo apt-get install python3-tkUbuntu或brew install python-tkmacOS否则报错No module named _tkinter。5. 作业提效用hw_checker.py自动验证 submission 格式与基础逻辑李宏毅作业提交有严格格式hwX_your_id.zip内必须含main.py、model.py、requirements.txt且main.py必须定义inference()函数。人工检查易漏我写了一个校验脚本# hw_checker.py import zipfile import ast import sys def check_hw_zip(zip_path): with zipfile.ZipFile(zip_path) as z: # 检查文件列表 required_files [main.py, model.py, requirements.txt] missing [f for f in required_files if f not in z.namelist()] if missing: print(f[✗] Missing files: {missing}) return False # 检查 main.py 是否含 inference 函数 with z.open(main.py) as f: tree ast.parse(f.read()) has_inference any( isinstance(node, ast.FunctionDef) and node.name inference for node in ast.walk(tree) ) if not has_inference: print([✗] main.py missing def inference() function) return False print([✓] Submission format OK) return True if __name__ __main__: check_hw_zip(sys.argv[1])运行python hw_checker.py hw1_b01234567.zip即可秒级反馈格式问题。比反复 zip → 提交 → 等 2 小时系统反馈快 10 倍。6. 进阶技巧把李宏毅的“debugging 思维”变成你的肌肉记忆李宏毅在 Lecture 1 开篇就说“Machine Learning is debugging, not math.” —— 这不是口号是方法论。他所有 notebook 的 cell 都暗藏 debug hook比如在forward()后插入print(fOutput shape: {x.shape})在loss.backward()后加print(fGrad norm: {torch.norm(model.parameters().__next__().grad)})。但新手常忽略这些 print或删掉后忘记恢复。我的做法是把 debug 语句封装成 context manager开关一键控制。# debug_utils.py from contextlib import contextmanager import torch contextmanager def debug_mode(enabledTrue): if not enabled: yield return # 记录 forward 输入输出形状 def hook_fn(module, input, output): print(f[DEBUG] {module.__class__.__name__}: {list(map(lambda x: x.shape, input))} - {output.shape}) handles [] for name, module in model.named_modules(): if len(list(module.children())) 0: # 只 hook 叶子模块 handles.append(module.register_forward_hook(hook_fn)) try: yield finally: for h in handles: h.remove() # 在训练 loop 中使用 with debug_mode(enabledTrue): # 设为 False 即关闭所有 debug print output model(input) loss criterion(output, target) loss.backward()这个debug_mode会在模型前向传播时自动打印每一层输入输出 shape帮你 3 秒定位维度错配比如Linear(128, 10)接Conv2d输出未 flatten。比手动加 print 高效且不会污染代码。另一个关键技巧用torch.autograd.set_detect_anomaly(True)捕获梯度异常源头。当 loss 突然 inf/nan普通loss.backward()只报错在最后一行而开启 anomaly detection 后错误栈会精确到x x / y中y为 0 的那一行。我在每个 homework 的train.py开头固定加torch.autograd.set_detect_anomaly(True) # 仅调试期开启正式训练关闭这让我在 HW3 的 speech command 任务中3 分钟定位到log_mel_spectrogram计算时stft的win_length与n_fft不匹配导致除零。最后一点血泪经验李宏毅课程所有“玄学”问题比如训练 loss 不下降、validation acc 波动大80% 源于random seed 未全局固定。他的 notebook 只在 data loader 设了generatortorch.Generator().manual_seed(42)但 optimizer、weight init 未锁。我的标准做法是def set_seed(seed42): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.deterministic True torch.backends.cudnn.benchmark False # 关闭 benchmark 获取确定性在 notebook 开头调用set_seed(42)所有实验结果即可复现。没有这行你调参三天可能只是运气好。希望帮到你。本文还有配套的精品资源点击获取

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑