Ainsteinx Logo
Ainsteinx
👤
欢迎使用 Ainsteinx
登录

切换语言

货币

首页
博客
服务
第 02 课 · 入门

深度学习基础

20 行代码讲清神经网络、损失函数和优化器。

神经网络就是矩阵乘法层与激活函数(ReLU)交替组成。训练就是用梯度下降和 Adam 等优化器调整权重,让损失变小。

示例在 8×8 手写数字(scikit-learn 自带,无需下载)上训练一个 MLP,准确率约 90%。

y = softmax( W₂ · ReLU( W₁·x + b₁ ) + b₂ ) loss = −Σ y_true · log y w ← w − lr · ∂loss/∂w
组件作用
Dense / Linear矩阵乘法 + 偏置
Conv2d用小卷积核在图像中寻找局部模式
BatchNorm · Dropout让训练更稳定、减少过拟合
Adam为每个权重自适应调整学习率的优化器

要点

  • 本系列的每个生成模型都由这些组件搭建而成
  • 每课之间主要变化的是损失函数
generative-ai-ep02-deep-learning.py
import torch, torch.nn as nn
from sklearn.datasets import load_digits

torch.manual_seed(0)
X, y = load_digits(return_X_y=True)                      # 1,797 images of 8x8 digits
X = torch.tensor(X / 16.0, dtype=torch.float32)
y = torch.tensor(y)
train, test = slice(0, 1400), slice(1400, None)

model = nn.Sequential(nn.Linear(64, 128), nn.ReLU(),
                      nn.Linear(128, 10))                  # 10 classes
opt = torch.optim.Adam(model.parameters(), lr=1e-2)
for epoch in range(60):
    loss = nn.functional.cross_entropy(model(X[train]), y[train])
    opt.zero_grad(); loss.backward(); opt.step()
    if epoch % 20 == 19:
        acc = (model(X[test]).argmax(1) == y[test]).float().mean()
        print(f"epoch {epoch + 1:2d}  loss {loss.item():.3f}  test acc {acc:.2%}")

输出结果

epoch 20  loss 0.158  test acc 87.66%
epoch 40  loss 0.042  test acc 89.67%
epoch 60  loss 0.020  test acc 90.93%
  • #GenerativeAI
  • #DeepLearning
  • #PythonສຳລັບຄົນLaos
  • #AI
  • #ບອກຕໍ່ຄວາມຮູ້