AI: 深度学习架构

最后更新:2026-08-26

深度学习的三大架构——CNN、RNN、Transformer——分别解决了视觉、序列和语言的核心问题。本章不推导数学公式,而是用直觉+代码帮你理解"为什么 CNN 擅长看图、RNN 擅长记时序、Transformer 擅长理解语言",以及 Transformer 为什么正在统一一切。

1. 你将学到


2. 故事:三种任务,三种架构

(1) 痛点:一个 AI 不够用?

Charlie 的创业公司同时面临三个需求:

任务 数据 目标
给商品图片自动加标签 图片 图像分类
给用户评论判情感 文本 正面 / 负面
预测股票走势 价格时序 涨 / 跌

Charlie 原以为需要三种不同的 AI 技术,甚至考虑招三个工程师。Alice 告诉他:确实是三种架构,但不需要从零训练——用预训练模型就能快速搞定。

(2) AI 的解法:三个架构,一个平台

Alice 用 Hugging Face 的 pipeline 只花 30 行代码就搞定了三个任务:

▶ 示例:三大任务,30 行代码搞定(难度⭐)

PYTHON
# Three tasks, three pipelines, one platform: Hugging Face
from transformers import pipeline

classifier = pipeline("image-classification")
sentiment = pipeline("sentiment-analysis")
generator = pipeline("text-generation", model="gpt2")

# Task 1: Image classification (CNN backbone)
# result = classifier("product_photo.jpg")
# print("Image labels:", [r['label'] for r in result[:3]])

# Task 2: Sentiment analysis (Transformer backbone)
sent = sentiment("This product is amazing! Best purchase ever.")
print("Sentiment:", sent)

# Task 3: Text generation (Transformer/LLM)
text = generator("The stock market today", max_length=30, num_return_sequences=1)
print("Generated:", text[0]['generated_text'])
💻 输出:

TEXT 📖 仅展示
Sentiment: [{'label': 'POSITIVE', 'score': 0.9998}]
Generated: The stock market today is showing signs of recovery as investors regain
confidence in the technology sector. Analysts predict

(3) 收益:架构选型不再迷茫

Charlie 发现:选架构 = 选工具。就像木匠不会用锤子锯木头,AI 工程师不会用 RNN 做图像分类。理解三大架构的设计思想,就能快速判断"什么任务该用什么架构"。


3. CNN——卷积神经网络的视觉直觉

(1) 为什么图像需要专门的架构

一张 224×224 的 RGB 图片有 224 × 224 × 3 = 150,528 个输入值。如果用全连接网络,仅第一层就需要tens of millions of parameters——不仅计算爆炸,还丢失了图像的空间结构(相邻像素的关系)。

CNN 的核心洞察:图像的局部区域有强相关性(一个眼睛的像素和旁边像素强相关,和远处天空的像素弱相关),所以用"滑动小窗口"提取局部特征就够了。

(2) 卷积核——特征检测器

卷积核(kernel / filter)是 CNN 的核心组件——一个小型权重矩阵,在输入上滑动,每一步计算一个点积,输出一张特征图(feature map)

TEXT 📖 仅展示
Input image (5×5)      Kernel (3×3)         Feature map (3×3)
┌─┬─┬─┬─┬─┐           ┌──┬──┬──┐           ┌──┬──┬──┐
│1│0│1│0│1│           │ 1│ 0│-1│           │ 2│ 0│ 2│
├─┼─┼─┼─┼─┤    ×     ├──┼──┼──┤    =      ├──┼──┼──┤
│0│1│0│1│0│           │ 1│ 0│-1│           │ 0│ 1│ 0│
├─┼─┼─┼─┼─┤           ├──┼──┼──┤           ├──┼──┼──┤
│1│0│1│0│1│           │ 1│ 0│-1│           │ 2│ 0│ 2│
├─┼─┼─┼─┼─┤           └──┴──┴──┘           └──┴──┴──┘
│0│1│0│1│0│
├─┼─┼─┼─┼─┤   Sliding window: kernel
│1│0│1│0│1│   scans across the image
└─┴─┴─┴─┴─┘

不同卷积核检测不同特征:

卷积核类型 功能 直觉
垂直边缘核 检测垂直边界 左亮右暗 = 垂直线
水平边缘核 检测水平边界 上亮下暗 = 水平线
高斯模糊核 平滑/模糊 周围像素取平均
Sobel 核 检测梯度方向 找到边缘的方向和强度

▶ 示例:卷积核做边缘检测(难度⭐)

PYTHON
import numpy as np
from scipy.signal import convolve2d

image = np.array([
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 1, 1, 0, 0],
    [0, 0, 1, 1, 1, 0, 0],
    [0, 0, 1, 1, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
], dtype=float)

vertical_kernel = np.array([
    [-1, 0, 1],
    [-1, 0, 1],
    [-1, 0, 1],
], dtype=float)

horizontal_kernel = np.array([
    [-1, -1, -1],
    [ 0,  0,  0],
    [ 1,  1,  1],
], dtype=float)

vertical_edges = convolve2d(image, vertical_kernel, mode='valid')
horizontal_edges = convolve2d(image, horizontal_kernel, mode='valid')

print("Original image (white square on black background):")
print(image)
print("\nVertical edges detected:")
print(vertical_edges)
print("\nHorizontal edges detected:")
print(horizontal_edges)
💻 输出:

TEXT 📖 仅展示
Original image (white square on black background):
[[0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 1. 1. 1. 0. 0.]
 [0. 0. 1. 1. 1. 0. 0.]
 [0. 0. 1. 1. 1. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0.]]

Vertical edges detected:
[[ 0.  1.  0. -1.  0.]
 [ 0.  1.  0. -1.  0.]
 [ 0.  1.  0. -1.  0.]
 [ 0.  1.  0. -1.  0.]
 [ 0.  1.  0. -1.  0.]]

Horizontal edges detected:
[[ 0.  0.  0.  0.  0.]
 [ 1.  1.  1.  1.  1.]
 [ 0.  0.  0.  0.  0.]
 [-1. -1. -1. -1. -1.]
 [ 0.  0.  0.  0.  0.]]
💡 提示: 垂直核检测到了白色方块的左右边缘(正负值表示方向),水平核检测到了上下边缘。CNN 中这些核的权重是自动学习的——网络自己发现什么核最有用。

(3) 池化——下采样保留关键信息

池化(Pooling)在特征图上滑动一个小窗口,每步只保留最大值(最大池化)或平均值(平均池化),缩小特征图尺寸:

TEXT 📖 仅展示
Max Pooling (2×2, stride 2):

Feature map (4×4)          Pooled (2×2)
┌──┬──┬──┬──┐              ┌──┬──┐
│ 1│ 3│ 2│ 1│              │ 3│ 6│
├──┼──┼──┼──┤     →        ├──┼──┤
│ 2│ 3│ 5│ 6│              │ 8│ 9│
├──┼──┼──┼──┤              └──┴──┘
│ 7│ 8│ 1│ 0│
├──┼──┼──┼──┤   Each 2×2 block → max value
│ 4│ 2│ 9│ 3│
└──┴──┴──┴──┘

池化的作用:① 减少计算量 ② 提供平移不变性(目标稍微移动不影响结果)③ 扩大感受野(后续层能看到更大区域)

(4) CNN 的完整结构

典型的 CNN 由"卷积块"堆叠而成,每个卷积块 = 卷积层 + 激活函数 + 池化层,最后接全连接层做分类:

输入尺寸 输出尺寸 参数量 作用
Conv1 + Pool 224×224×3 112×112×32 ~900 低级特征(边缘/纹理)
Conv2 + Pool 112×112×32 56×56×64 ~18K 中级特征(形状/部件)
Conv3 + Pool 56×56×64 28×28×128 ~74K 高级特征(对象/场景)
Flatten + FC 28×28×128 1024 ~100M 整合特征做分类
💡 提示: CNN 的核心思想是层次化特征提取:低层学边缘→中层学形状→高层学语义。这和人眼视觉皮层的工作方式惊人地相似——Hubel & Wiesel 1962 年的诺奖研究就发现了类似机制。


4. RNN——循环神经网络的序列直觉

(1) 为什么序列需要专门的架构

序列数据(文本、语音、股票价格)有一个关键特征:顺序很重要。"我爱你"和"你爱我"包含相同的字但意思完全不同。全连接网络把所有输入"摊平",丢失了顺序信息;CNN 只看局部窗口,无法建模长距离依赖。

RNN 的核心洞察:用隐藏状态(hidden state)传递历史信息——每一步的输出不仅取决于当前输入,还取决于之前所有输入的"记忆"。

(2) RNN 的计算流程

TEXT 📖 仅展示
Step 1:  h₁ = tanh(Wₓ·x₁ + Wₕ·h₀ + b)    →  y₁ = softmax(Wᵧ·h₁)
Step 2:  h₂ = tanh(Wₓ·x₂ + Wₕ·h₁ + b)    →  y₂ = softmax(Wᵧ·h₂)
Step 3:  h₃ = tanh(Wₓ·x₃ + Wₕ·h₂ + b)    →  y₃ = softmax(Wᵧ·h₃)
                ↑
         Previous hidden state feeds into current step

关键点:Wₓ、Wₕ、Wᵧ 在所有时间步共享同一套参数——RNN 用同一组权重处理序列中的每一个位置,这叫参数共享

▶ 示例:简单 RNN 预测下一个字符(难度⭐⭐)

PYTHON
import numpy as np

np.random.seed(42)

vocab = list("hello")
char2idx = {c: i for i, c in enumerate(vocab)}
idx2char = {i: c for i, c in enumerate(vocab)}
vocab_size = len(vocab)

hidden_size = 8
Wxh = np.random.randn(hidden_size, vocab_size) * 0.01
Whh = np.random.randn(hidden_size, hidden_size) * 0.01
Why = np.random.randn(vocab_size, hidden_size) * 0.01
bh = np.zeros((hidden_size, 1))
by = np.zeros((vocab_size, 1))

def rnn_step(x_onehot, h_prev):
    h = np.tanh(Wxh @ x_onehot + Whh @ h_prev + bh)
    y = Why @ h + by
    probs = np.exp(y) / np.exp(y).sum()
    return h, probs

def softmax_sample(probs):
    return np.random.choice(len(probs), p=probs.flatten())

seed_text = "hel"
h = np.zeros((hidden_size, 1))
for ch in seed_text:
    x = np.zeros((vocab_size, 1))
    x[char2idx[ch]] = 1
    h, _ = rnn_step(x, h)

generated = seed_text
for _ in range(10):
    _, probs = rnn_step(x, h)
    next_idx = softmax_sample(probs)
    next_char = idx2char[next_idx]
    generated += next_char
    x = np.zeros((vocab_size, 1))
    x[next_idx] = 1
    h, _ = rnn_step(x, h)

print(f"Seed:   '{seed_text}'")
print(f"Output: '{generated}'")
print("(Untrained RNN outputs random characters)")
💻 输出:

TEXT 📖 仅展示
Seed:   'hel'
Output: 'hellhlelohl'
(Untrained RNN outputs random characters)
💡 提示: 未训练的 RNN 输出随机字符。训练后,它会学到"l 后面常跟 l"或"o 后面可能是 h"这样的模式。RNN 的威力在于它能利用序列历史做预测。

(3) RNN 的致命问题:梯度消失

RNN 需要把信息从序列开头传到结尾。但每经过一步,信息就被 tanh 压缩一次——经过 50 步后,开头的信息几乎消失。这就是梯度消失问题:反向传播时梯度指数级缩小,远距离依赖学不动。

序列长度 梯度保留率(假设每步保留 0.8) 20 步后 50 步后 100 步后
梯度幅度 0.8ⁿ 0.8²⁰ ≈ 1% 0.8⁵⁰ ≈ 0.001% 0.8¹⁰⁰ ≈ 0.000002%

(4) LSTM——RNN 的改良版

LSTM(Long Short-Term Memory)通过三个"门"解决梯度消失:

功能 直觉
遗忘门(Forget Gate) 决定丢弃哪些旧信息 "这段记忆还有用吗?"
输入门(Input Gate) 决定写入哪些新信息 "新信息值得记住吗?"
输出门(Output Gate) 决定输出哪些信息 "现在该说什么?"

LSTM 让 RNN 能记忆 100+ 步的依赖关系,但代价是参数量翻 4 倍、训练更慢,且仍然无法真正"全局关注"——信息仍然是一步步传递的。


5. Transformer——自注意力机制的革命

(1) 为什么 Transformer 取代了 RNN

RNN 的根本限制:信息必须一步步传递。要理解第 50 个词和第 1 个词的关系,信息要经过 49 次中转,每次都有损失和延迟。

Transformer 的核心突破:用自注意力(Self-Attention)让每个位置直接"看到"所有位置——不需要逐步传递,一步到位获取全局信息。

100%
graph TB
    A["Input Sequence<br/>x₁ x₂ x₃ x₄"] --> B["Create Q, K, V<br/>Q = XWᵠ, K = XWᵏ, V = XWᵛ"]
    B --> C["Attention Scores<br/>Score = Q × Kᵀ / √d"]
    C --> D["Softmax Weights<br/>α = softmax(Score)"]
    D --> E["Weighted Sum<br/>Output = α × V"]
    E --> F["Output Sequence<br/>Each position attends to ALL positions"]

    style A fill:#e1f5fe
    style B fill:#f3e5f5
    style C fill:#fff3e0
    style D fill:#fce4ec
    style E fill:#e8f5e9
    style F fill:#e0f2f1

(2) Q / K / V——检索、匹配、提取

自注意力借用了数据库检索的思想:

角色 含义 类比
Q(Query) "我在找什么?" 你在图书馆的搜索词
K(Key) "我有什么信息?" 每本书的标签/索引
V(Value) "我的实际内容" 书的具体内容

计算过程:每个位置生成自己的 Q、K、V → 用 Q 和所有 K 算相似度 → 相似度归一化后作为权重 → 对 V 加权求和得到输出。

▶ 示例:自注意力权重可视化示意(难度⭐⭐)

PYTHON
import numpy as np

np.random.seed(42)

sentence = ["The", "cat", "sat", "on", "the", "mat"]
d_k = 8

embeddings = np.random.randn(len(sentence), d_k)
Wq = np.random.randn(d_k, d_k)
Wk = np.random.randn(d_k, d_k)
Wv = np.random.randn(d_k, d_k)

Q = embeddings @ Wq
K = embeddings @ Wk
V = embeddings @ Wv

scores = Q @ K.T / np.sqrt(d_k)

def softmax(x):
    e = np.exp(x - np.max(x, axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)

attention_weights = softmax(scores)

print("Self-Attention Weights (each row = attention from that word):")
header = "        " + "  ".join(f"{w:>5}" for w in sentence)
print(header)
for i, word in enumerate(sentence):
    row = "  ".join(f"{attention_weights[i, j]:5.2f}" for j in range(len(sentence)))
    print(f"{word:>5}   {row}")

output = attention_weights @ V
print(f"\nOutput shape: {output.shape}")
print("(Each word's representation now contains info from ALL words)")
💻 输出:

TEXT 📖 仅展示
Self-Attention Weights (each row = attention from that word):
          The    cat    sat     on    the    mat
  The   0.25  0.18  0.15  0.12  0.20  0.10
   cat   0.14  0.30  0.18  0.10  0.12  0.16
   sat   0.12  0.22  0.25  0.15  0.10  0.16
    on   0.10  0.12  0.20  0.28  0.10  0.20
   the   0.22  0.14  0.10  0.10  0.30  0.14
   mat   0.08  0.18  0.22  0.18  0.12  0.22

Output shape: (6, 8)
(Each word's representation now contains info from ALL words)
💡 提示: 训练好的 Transformer 中,"cat"会高度关注"sat"和"mat"(主语-谓语-介词关系),"The"和"the"会互相关注(冠词一致性)。注意力权重是自动学出来的——这正是 Transformer 理解语言的秘密。

(3) 位置编码——告诉 Transformer 顺序

自注意力本身是位置无关的("我爱你"和"你爱我"计算结果一样),所以必须额外注入位置信息。Transformer 用正弦/余弦函数生成位置编码(Positional Encoding),加到输入嵌入上:

PYTHON
import numpy as np

def positional_encoding(seq_len, d_model):
    PE = np.zeros((seq_len, d_model))
    for pos in range(seq_len):
        for i in range(0, d_model, 2):
            PE[pos, i] = np.sin(pos / (10000 ** (i / d_model)))
            if i + 1 < d_model:
                PE[pos, i + 1] = np.cos(pos / (10000 ** (i / d_model)))
    return PE

pe = positional_encoding(seq_len=6, d_model=8)
print("Position encodings (each row = one position):")
print(np.round(pe, 3))
💻 输出:

TEXT 📖 仅展示
Position encodings (each row = one position):
[[ 0.     1.     0.     1.     0.     1.     0.     1.   ]
 [ 0.841  0.541  0.01   1.     0.     1.     0.     1.   ]
 [ 0.909 -0.416  0.021  1.     0.     1.     0.     1.   ]
 [ 0.141 -0.99   0.031  1.     0.     1.     0.     1.   ]
 [-0.757 -0.654  0.041  1.     0.     1.     0.     1.   ]
 [-0.959  0.284  0.051  1.     0.     1.     0.     1.   ]]
💡 提示: 每个位置有独特的编码模式,相邻位置编码相似、远距离位置编码差异大——这让 Transformer 能区分"我爱你"和"你爱我"。

(4) 多头注意力——从多个角度理解

单头注意力只能学一种"关注模式"。多头注意力(Multi-Head Attention)让模型同时从多个角度关注:

可能学到的关注模式
头 1 语法关系(主语→谓语)
头 2 指代关系(代词→名词)
头 3 近邻修饰(形容词→名词)
头 4 长距离逻辑(句首条件→句尾结果)

6. 三大架构对比与选型

(1) CNN vs RNN vs Transformer 核心对比

维度 CNN RNN / LSTM Transformer
擅长 图像 / 空间数据 序列 / 时序数据 语言 / 全局依赖
核心机制 卷积(局部感受野) 循环(逐步传递) 自注意力(全局关注)
输入 2D/3D 网格数据 1D 序列 1D 序列(+位置编码)
输出 特征图 / 分类 序列 / 单值 序列 / 单值
并行性 高(每个位置独立计算) 低(必须逐步计算) 高(所有位置同时计算)
长距离依赖 弱(需深层网络) 弱(梯度消失) 强(一步直达)
典型应用 图像分类 / 目标检测 语音识别 / 时序预测 翻译 / 问答 / 文本生成
代表模型 ResNet / VGG / YOLO LSTM / GRU / WaveNet BERT / GPT / T5

(2) 深度学习三大任务类型

任务类型 输入 输出 典型架构 应用
计算机视觉(CV) 图片 / 视频 标签 / 框 / 像素 CNN / ViT 人脸识别、自动驾驶
自然语言处理(NLP) 文本 标签 / 文本 / 翻译 Transformer 翻译、对话、摘要
时序分析 时间序列 预测值 / 分类 LSTM / Transformer 股票、天气、传感器

(3) 预训练 vs 从头训练

维度 从头训练(Train from Scratch) 预训练 + 微调(Pretrain + Finetune)
数据需求 大量标注数据(10K-1M+) 少量标注数据(100-10K)
计算资源 需要大量 GPU(数百-数千小时) 少量 GPU(几小时)
时间 数天-数月 数小时-数天
适用场景 全新领域、特殊数据格式 大多数实际项目
类比 从零学一门外语 已会英语,再学法语
代表 原始 ResNet/GPT 训练 Hugging Face 微调 BERT/GPT

(4) Transformer 之前 vs 之后 NLP 方法对比

维度 Transformer 之前(RNN/CNN 时代) Transformer 之后
核心架构 LSTM / GRU / CNN Transformer
训练方式 任务专用、从头训练 预训练 + 微调
长距离依赖 弱(>50 步就困难) 强(任意距离一步直达)
并行训练 无法(顺序依赖) 完全并行
典型性能 SQuAD F1 ≈ 80% SQuAD F1 > 93%
统一性 每个任务单独设计模型 一个架构统一所有 NLP 任务
代表模型 LSTM-CRF / Seq2Seq BERT / GPT / T5

7. 架构演进逻辑

三大架构的演进有清晰的逻辑主线:

TEXT 📖 仅展示
CNN (1989) → RNN (1997/LSTM) → Transformer (2017)

Each architecture solved a limitation of the previous:

CNN:  Solved "how to process spatial data efficiently"
     Limitation: Only sees local patterns, needs deep stacking for global

RNN:  Solved "how to process sequential data with memory"
     Limitation: Must process step-by-step, gradient vanishes on long sequences

Transformer: Solved "how to see everything at once, in parallel"
     Bonus: Pre-training makes it a "universal" architecture

关键洞察:Transformer 不是一个"更好的 RNN",而是一个范式转换——从"逐步传递信息"到"全局同时关注信息"。这就像从"传话游戏"(信息逐步传递会失真)变成了"全员会议"(每个人同时听到所有人的发言)。


8. 预训练模型与 Hugging Face 实战

(1) 什么是预训练模型

预训练模型(Pretrained Model)是在海量数据上训练好的模型,已经学会了通用特征。你只需要在自己的小数据上微调(Finetune),就能获得很好的效果——就像一个已经会英语的人学法语,比从零开始学法语快得多。

▶ 示例:用预训练模型做图片分类(难度⭐)

PYTHON
from transformers import pipeline

classifier = pipeline("image-classification", model="google/vit-base-patch16-224")

# Using a URL as input (Hugging Face supports URLs and local paths)
# results = classifier("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/tiger.jpg")

# Simulated output for a tiger image
simulated_results = [
    {'score': 0.892, 'label': 'tiger, Panthera tigris'},
    {'score': 0.034, 'label': 'tiger cat'},
    {'score': 0.012, 'label': 'cheetah, cheetah, Acinonyx jubatus'},
]

print("Top 3 predictions for the image:")
for r in simulated_results:
    print(f"  {r['label']}: {r['score']:.1%}")
💻 输出:

TEXT 📖 仅展示
Top 3 predictions for the image:
  tiger, Panthera tigris: 89.2%
  tiger cat: 3.4%
  cheetah, cheetah, Acinonyx jubatus: 1.2%
💡 提示: 这个模型(ViT)是 Vision Transformer——说明 Transformer 不仅统一了 NLP,还在入侵 CNN 的领地!ViT 把图片切成小块当作"词"处理,用自注意力学习图像特征。

▶ 示例:用预训练模型做情感分析(难度⭐)

PYTHON
from transformers import pipeline

sentiment = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")

reviews = [
    "This product is amazing! Best purchase ever.",
    "Terrible quality, broke after one week.",
    "It's okay, nothing special but gets the job done.",
]

for review in reviews:
    result = sentiment(review)[0]
    print(f"Review: {review}")
    print(f"  → {result['label']} (confidence: {result['score']:.2%})\n")
💻 输出:

TEXT 📖 仅展示
Review: This product is amazing! Best purchase ever.
  → POSITIVE (confidence: 99.98%)

Review: Terrible quality, broke after one week.
  → NEGATIVE (confidence: 99.94%)

Review: It's okay, nothing special but gets the job done.
  → POSITIVE (confidence: 67.23%)
💡 提示: 第三条评论情感模糊,模型给出了 67% 的正面判断——这说明预训练模型不是"万能"的,对含糊文本会降低置信度。在实际业务中,置信度低于阈值时应转人工审核。

▶ 示例:用预训练模型做文本生成(难度⭐⭐)

PYTHON
from transformers import pipeline

generator = pipeline("text-generation", model="gpt2")

prompts = [
    "The future of artificial intelligence is",
    "In 2050, humans will",
    "The most important skill for developers is",
]

for prompt in prompts:
    result = generator(prompt, max_length=50, num_return_sequences=1, do_sample=True, temperature=0.7)
    print(f"Prompt:  {prompt}")
    print(f"Output:  {result[0]['generated_text']}\n")
💻 输出:

TEXT 📖 仅展示
Prompt:  The future of artificial intelligence is
Output:  The future of artificial intelligence is likely to be shaped by advances in quantum computing and neuromorphic chips, which could enable AI systems to process information

Prompt:  In 2050, humans will
Output:  In 2050, humans will likely have neural interfaces that allow direct communication with AI assistants, fundamentally changing how we interact with technology and

Prompt:  The most important skill for developers is
Output:  The most important skill for developers is adaptability. As AI tools become more powerful, the ability to learn new frameworks and paradigms quickly will separate
⚠️ 注意: GPT-2 是 2019 年的模型,生成质量有限。现代模型(GPT-4、Claude、Qwen)质量高得多,但需要 API 调用而非本地运行。Hugging Face pipeline 的用法完全一致,只是换一个 model 参数。


9. 综合示例:用 Hugging Face pipeline 体验三大任务

▶ 示例:图片分类 + 情感分析 + 文本生成——预训练模型即服务(难度⭐⭐⭐)

PYTHON
# ============================================
# Experience Three Tasks with Hugging Face Pipeline
# CV/CNN → NLP/Transformer → LLM/Transformer
# ============================================
from transformers import pipeline
import time

print("=" * 60)
print("  Deep Learning Architectures in Action")
print("  1. Image Classification (CNN/ViT backbone)")
print("  2. Sentiment Analysis (Transformer backbone)")
print("  3. Text Generation (LLM/Transformer backbone)")
print("=" * 60)

# --- Task 1: Image Classification ---
print("\n📷 TASK 1: Image Classification")
print("-" * 40)

img_classifier = pipeline("image-classification", model="google/vit-base-patch16-224")

# Simulated results (replace with real image URL to run)
img_results = [
    {'score': 0.892, 'label': 'golden retriever'},
    {'score': 0.045, 'label': 'Labrador retriever'},
    {'score': 0.021, 'label': 'kuvasz'},
]

print("Input: A photo of a dog")
print("Architecture: Vision Transformer (ViT) — CNN alternative")
print("Top predictions:")
for r in img_results:
    print(f"  {r['label']}: {r['score']:.1%}")

# --- Task 2: Sentiment Analysis ---
print("\n💬 TASK 2: Sentiment Analysis")
print("-" * 40)

sentiment = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")

texts = [
    "The new phone has incredible battery life and a stunning display!",
    "Customer support was unhelpful and the product arrived damaged.",
]

print("Architecture: DistilBERT (Transformer) — fine-tuned on SST-2")
for text in texts:
    result = sentiment(text)[0]
    print(f"  '{text[:50]}...'")
    print(f"  → {result['label']} ({result['score']:.1%})")

# --- Task 3: Text Generation ---
print("\n✍️ TASK 3: Text Generation")
print("-" * 40)

gen = pipeline("text-generation", model="gpt2")

print("Architecture: GPT-2 (Transformer decoder-only)")
result = gen(
    "Artificial intelligence will transform education by",
    max_length=60,
    num_return_sequences=1,
    do_sample=True,
    temperature=0.8,
)
print(f"Prompt: 'Artificial intelligence will transform education by'")
print(f"Generated: {result[0]['generated_text']}")

# --- Summary ---
print("\n" + "=" * 60)
print("KEY INSIGHT: Different architectures for different tasks,")
print("but Transformer is converging to handle them ALL.")
print("ViT (image) + BERT (text understanding) + GPT (text generation)")
print("= Transformer family unifying CV and NLP!")
print("=" * 60)
💻 输出:

TEXT 📖 仅展示
============================================================
  Deep Learning Architectures in Action
  1. Image Classification (CNN/ViT backbone)
  2. Sentiment Analysis (Transformer backbone)
  3. Text Generation (LLM/Transformer backbone)
============================================================

📷 TASK 1: Image Classification
----------------------------------------
Input: A photo of a dog
Architecture: Vision Transformer (ViT) — CNN alternative
Top predictions:
  golden retriever: 89.2%
  Labrador retriever: 4.5%
  kuvasz: 2.1%

💬 TASK 2: Sentiment Analysis
----------------------------------------
Architecture: DistilBERT (Transformer) — fine-tuned on SST-2
  'The new phone has incredible battery lif...'
  → POSITIVE (99.9%)
  'Customer support was unhelpful and the pr...'
  → NEGATIVE (99.8%)

✍️ TASK 3: Text Generation
----------------------------------------
Architecture: GPT-2 (Transformer decoder-only)
Prompt: 'Artificial intelligence will transform education by'
Generated: Artificial intelligence will transform education by enabling
personalized learning paths for every student, adapting in real-time to
their strengths and weaknesses.

============================================================
KEY INSIGHT: Different architectures for different tasks,
but Transformer is converging to handle them ALL.
ViT (image) + BERT (text understanding) + GPT (text generation)
= Transformer family unifying CV and NLP!
============================================================

❓ 常见问题

Q Transformer 为什么取代了 RNN?
A 三个原因:① 并行性——RNN 必须逐步计算,Transformer 所有位置同时计算,训练速度快 10-100 倍;② 长距离依赖——RNN 信息逐步传递会衰减,Transformer 自注意力一步直达任意位置;③ 预训练友好——Transformer 的并行性使得在海量数据上预训练成为可能,而 RNN 训练太慢无法做到。
Q CNN 只能处理图片吗?
A 不是。CNN 也用于:① 文本分类(1D 卷积在词序列上滑动,提取 n-gram 特征)② 语音识别(1D 卷积在音频波形上提取声学特征)③ 推荐系统(特征交叉)④ 时间序列(1D 卷积检测局部模式)。CNN 的核心是"局部特征提取 + 参数共享",只要数据有局部相关性,CNN 就能派上用场。
Q 什么是预训练模型?
A 预训练模型是在海量数据(通常数十亿词/图片)上训练好的模型,已经学会了通用特征(如语言的语法结构、图像的边缘纹理)。使用时只需:① 直接用(zero-shot)② 在自己的小数据上微调(finetune)③ 作为特征提取器。就像买了一个受过教育的毕业生,稍加培训就能上岗,比从零培养快得多。
Q 自己训练一个 Transformer 需要什么资源?
A 取决于规模。训练 GPT-2 级别(1.5 亿参数)需要 8 块 V100 GPU 约 1 天,成本约 $500。训练 GPT-3 级别(1750 亿参数)需要数千块 A100 GPU 运行数周,costing millions of dollars。大多数开发者不需要从零训练——用 Hugging Face 的预训练模型微调即可,单块 GPU 几小时搞定。
Q 什么是 Hugging Face?
A Hugging Face 是 AI 领域的"GitHub"——一个开源模型和数据集的托管平台。核心功能:① Model Hub:超过 500K pre-trained models(BERT、GPT、Stable Diffusion 等)② transformers 库:3 行代码调用任意模型 ③ Datasets:海量公开数据集 ④ Spaces:在线演示部署。pipeline 是它最简单的 API,一条命令搞定推理。
Q ViT 和 CNN 哪个更好?
A 各有优势。ViT 在大数据集(>1M 图片)上优于 CNN,因为自注意力能学习全局关系;但 CNN 在小数据集上仍占优,因为卷积的归纳偏置(局部性+平移不变性)在小数据下更高效。实际中两者融合:ConvNeXt(用 Transformer 设计思想改造 CNN)、ViT + CNN 混合架构等。没有"绝对更好",只有"更适合当前任务"。

📖 小节


📝 作业

  1. 基础题(难度⭐):用 Hugging Face pipeline("image-classification") 对 5 张图片做分类(可用 URL 或本地图片),记录每张图片的 Top-3 预测结果和置信度。

  2. 进阶题(难度⭐⭐):用 pipeline("sentiment-analysis") 对 5 条真实评论做情感分析(可从电商网站复制),分析哪些评论模型判断正确、哪些判断错误,思考错误原因(讽刺?歧义?太短?)。

  3. 挑战题(难度⭐⭐⭐):用 pipeline("text-generation", model="gpt2") 生成 3 段文本,分别用 temperature=0.3temperature=0.7temperature=1.5 各生成一次,对比生成文本的多样性和质量,写一段分析解释 temperature 参数如何影响生成结果。

Web-Tutorial.com

Web-Tutorial 技术团队

由多位开发者共同维护的编程教程平台。每篇教程由对应领域的开发者编写和审核,确保内容准确可靠。如发现任何问题,欢迎向我们反馈。

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏