Skip to content

Hugging Face NLP Course 第 1 模块中英对照

课程: Hugging Face NLP Course
原链接: https://huggingface.co/learn/nlp-course/chapter1/1
版本: transformers >= 4.40.0
翻译时间: 2026-06-01
状态: 中英对照编译版


📚 目录 (Table of Contents)

Module 1: Introduction to NLP and Transformers

模块 1: NLP 与 Transformer 简介

  • Chapter 1/1: Introduction (引言)
  • Chapter ½: What is NLP? (什么是 NLP?)
  • Chapter ⅓: Transformers and Hugging Face (Transformer 与 Hugging Face)
  • Chapter ¼: Using Pipelines (使用 Pipeline)
  • Chapter ⅕: Understanding Tokenizers (理解 Tokenizer)
  • Chapter ⅙: Handling Long Sequences (处理长序列)

Chapter 1/1: Introduction

第 1/1 章:引言

English:

Welcome to the Hugging Face NLP Course! This course will teach you how to use the Hugging Face ecosystem to solve natural language processing tasks. By the end of this course, you will be able to:

  • Use pretrained models for various NLP tasks
  • Fine-tune models on your own datasets
  • Understand the Transformer architecture
  • Deploy models to production

中文:

欢迎来到 Hugging Face NLP 课程!本课程将教你如何使用 Hugging Face 生态系统解决自然语言处理任务。课程结束时,你将能够:

  • 使用预训练模型完成各种 NLP 任务
  • 在你自己的数据集上微调模型
  • 理解 Transformer 架构
  • 将模型部署到生产环境

学习前提 (Prerequisites):

技能 英文 必要性
Python 编程 Python programming ⭐⭐⭐ 必需
深度学习基础 Deep learning basics ⭐⭐ 推荐
PyTorch/TensorFlow PyTorch/TensorFlow ⭐⭐ 推荐
命令行使用 Command line usage ⭐ 有帮助

Chapter ½: What is NLP?

第 ½ 章:什么是 NLP?

English:

Natural Language Processing (NLP) is a branch of artificial intelligence that deals with the interaction between computers and human language. The goal of NLP is to enable computers to understand, interpret, and generate human language.

中文:

自然语言处理 (NLP) 是人工智能的一个分支,处理计算机与人类语言之间的交互。NLP 的目标是使计算机能够理解、解释和生成人类语言。

常见 NLP 任务 (Common NLP Tasks):

任务 英文 中文 示例
文本分类 Text Classification 将文本分类到预定义类别 情感分析、垃圾邮件检测
命名实体识别 Named Entity Recognition 识别文本中的实体 人名、地名、组织名
问答系统 Question Answering 回答问题 客服机器人
文本生成 Text Generation 生成连贯文本 文章写作、代码生成
翻译 Translation 语言间翻译 英译中、中译日
摘要 Summarization 生成文本摘要 新闻摘要、论文摘要

Chapter ⅓: Transformers and Hugging Face

第 ⅓ 章:Transformer 与 Hugging Face

Transformer 架构 (Transformer Architecture)

English:

The Transformer architecture, introduced in the paper "Attention Is All You Need" (2017), revolutionized NLP. Unlike previous recurrent neural networks (RNNs), Transformers use self-attention mechanisms to process sequences in parallel, making them much faster to train.

中文:

Transformer 架构在论文《Attention Is All You Need》(2017) 中提出,彻底改变了 NLP。与之前的循环神经网络 (RNN) 不同,Transformer 使用自注意力机制并行处理序列,使训练速度快得多。

Transformer 优势 (Advantages):

┌─────────────────────────────────────────────┐
│ Transformer vs RNN/LSTM                     │
├─────────────────────────────────────────────┤
│ ✓ 并行处理 (Parallel processing)            │
│ ✓ 长距离依赖 (Long-range dependencies)      │
│ ✓ 训练速度快 (Faster training)              │
│ ✓ 效果更好 (Better performance)             │
│ ✗ 需要更多内存 (Requires more memory)       │
│ ✗ 位置编码复杂 (Complex positional encoding)│
└─────────────────────────────────────────────┘

Hugging Face 生态系统 (Hugging Face Ecosystem)

English:

Hugging Face provides a suite of libraries that make NLP accessible to everyone:

  • 🤗 Transformers: State-of-the-art models
  • 🤗 Datasets: Easy access to datasets
  • 🤗 Tokenizers: Fast tokenization
  • 🤗 Accelerate: Hardware acceleration
  • 🤗 Hub: Model and dataset sharing

中文:

Hugging Face 提供一套使 NLP 对人人可及的库:

  • 🤗 Transformers:最先进的模型
  • 🤗 Datasets:轻松访问数据集
  • 🤗 Tokenizers:快速分词
  • 🤗 Accelerate:硬件加速
  • 🤗 Hub:模型和数据集共享

库安装 (Library Installation):

# 安装核心库
pip install transformers datasets accelerate

# 安装深度学习框架(二选一)
pip install torch  # PyTorch
pip install tensorflow  # TensorFlow

# 验证安装
python -c "import transformers; print(transformers.__version__)"

Chapter ¼: Using Pipelines

第 ¼ 章:使用 Pipeline

Pipeline API 简介 (Pipeline API Introduction)

English:

The pipeline() API is the easiest way to use pretrained models. It abstracts away the complexity of preprocessing, model inference, and postprocessing.

中文:

pipeline() API 是使用预训练模型的最简单方法。它抽象掉了预处理、模型推理和后处理的复杂性。

快速开始 (Quick Start)

# 英文示例
from transformers import pipeline

# 情感分析
classifier = pipeline("sentiment-analysis")
result = classifier("I love learning about NLP!")
print(result)  # [{'label': 'POSITIVE', 'score': 0.9998}]

# 中文示例
classifier = pipeline("sentiment-analysis", model="bert-base-chinese")
result = classifier("我喜欢学习 NLP!")
print(result)

支持的任务 (Supported Tasks)

English:

The pipeline API supports many tasks out of the box:

中文:

pipeline API 开箱即用地支持多种任务:

任务 管道名称 代码示例
情感分析 sentiment-analysis pipeline("sentiment-analysis")
文本分类 text-classification pipeline("text-classification")
命名实体识别 token-classification pipeline("token-classification")
问答 question-answering pipeline("question-answering")
文本生成 text-generation pipeline("text-generation")
摘要 summarization pipeline("summarization")
翻译 translation pipeline("translation_en_to_fr")

完整示例 (Complete Examples)

1. 情感分析 (Sentiment Analysis):

from transformers import pipeline

# 使用默认模型
classifier = pipeline("sentiment-analysis")

# 单条预测
result = classifier("This movie was amazing!")
# [{'label': 'POSITIVE', 'score': 0.99987}]

# 批量预测
results = classifier(["I love it!", "I hate it."])
# [{'label': 'POSITIVE', 'score': 0.9998}, 
#  {'label': 'NEGATIVE', 'score': 0.9987}]

2. 命名实体识别 (Named Entity Recognition):

from transformers import pipeline

ner = pipeline("token-classification")
result = ner("Elon Musk is the CEO of Tesla.")

# 输出:
# [{'entity': 'B-PER', 'word': 'Elon', 'score': 0.99},
#  {'entity': 'I-PER', 'word': 'Musk', 'score': 0.99},
#  {'entity': 'B-ORG', 'word': 'Tesla', 'score': 0.98}]

3. 问答 (Question Answering):

from transformers import pipeline

qa = pipeline("question-answering")
result = qa(
    question="What is NLP?",
    context="NLP stands for Natural Language Processing. It is a field of AI."
)

# 输出:
# {'score': 0.95, 'start': 17, 'end': 48, 
#  'answer': 'Natural Language Processing'}

Chapter ⅕: Understanding Tokenizers

第 ⅕ 章:理解 Tokenizer

什么是 Tokenizer?(What is a Tokenizer?)

English:

A tokenizer converts text into numbers that a model can understand. It does this in three steps: 1. Splitting the text into words or subwords (tokens) 2. Converting tokens to token IDs 3. Adding special tokens and attention masks

中文:

Tokenizer 将文本转换为模型可以理解的数字。它分三步完成: 1. 将文本分割为单词或子词(token) 2. 将 token 转换为 token ID 3. 添加特殊 token 和注意力掩码

Tokenization 流程 (Tokenization Process)

原始文本 → 分词 → Token IDs → 模型输入
"I love NLP" → ["I", "love", "NLP"] → [1045, 2293, 19205] → [1045, 2293, 19205]

Tokenizer 类型 (Tokenizer Types)

English:

There are several tokenization strategies:

中文:

有几种分词策略:

类型 英文 中文 说明
Word-based Word-based 基于词 每个单词一个 token
Character-based Character-based 基于字符 每个字符一个 token
Subword Subword 子词 常用词完整,罕见词拆分

实践示例 (Practical Examples)

from transformers import AutoTokenizer

# 加载 tokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")

# 文本
text = "I love natural language processing"

# 方法 1: 直接编码
encoding = tokenizer(text)
print(encoding)
# {'input_ids': [1045, 2293, 3793, 2618, 19205], 
#  'attention_mask': [1, 1, 1, 1, 1],
#  'token_type_ids': [0, 0, 0, 0, 0]}

# 方法 2: 分步处理
tokens = tokenizer.tokenize(text)
print(tokens)  # ['i', 'love', 'natural', 'language', 'processing']

ids = tokenizer.convert_tokens_to_ids(tokens)
print(ids)  # [1045, 2293, 3793, 2618, 19205]

# 解码回文本
decoded = tokenizer.decode(ids)
print(decoded)  # 'i love natural language processing'

特殊 Token (Special Tokens)

English:

Special tokens have specific meanings:

中文:

特殊 token 有特定含义:

Token 名称 用途
[CLS] Classification 分类任务的聚合 token
[SEP] Separator 分隔两个句子
[PAD] Padding 填充到相同长度
[UNK] Unknown 未知词
[MASK] Mask 用于掩码语言模型

Chapter ⅙: Handling Long Sequences

第 ⅙ 章:处理长序列

序列长度限制 (Sequence Length Limit)

English:

Transformer models have a maximum sequence length (e.g., 512 tokens for BERT). Longer sequences need special handling.

中文:

Transformer 模型有最大序列长度限制(如 BERT 为 512 个 token)。更长的序列需要特殊处理。

处理策略 (Handling Strategies)

1. 截断 (Truncation):

from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
long_text = "This is a very long text... " * 100

# 自动截断
encoding = tokenizer(
    long_text,
    truncation=True,
    max_length=512
)
print(len(encoding['input_ids']))  # 512

2. 分块 (Chunking):

def process_long_text(text, max_length=512):
    tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")

    # 分块处理
    chunks = []
    words = text.split()

    for i in range(0, len(words), max_length):
        chunk = ' '.join(words[i:i+max_length])
        chunks.append(chunk)

    # 分别编码每个块
    encodings = [tokenizer(chunk, return_tensors='pt') for chunk in chunks]

    return encodings

# 使用
encodings = process_long_text(very_long_text)

3. 滑动窗口 (Sliding Window):

def sliding_window_encode(text, window_size=512, stride=256):
    tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")

    encodings = tokenizer(
        text,
        max_length=window_size,
        stride=stride,
        return_overflowing_tokens=True
    )

    return encodings

不同模型的最大长度 (Max Length by Model)

模型 最大长度 说明
BERT 512 标准编码器
GPT-2 1024 解码器模型
GPT-¾ 2048-128K 大语言模型
Longformer 4096+ 长文档专用
LED 16384 长编码器 - 解码器

🛠️ 实践练习 (Hands-on Exercises)

练习 1: 情感分析 (Exercise 1: Sentiment Analysis)

from transformers import pipeline

# 创建情感分析 pipeline
classifier = pipeline("sentiment-analysis")

# 分析以下文本
texts = [
    "This product is amazing!",
    "I'm very disappointed with the service.",
    "The movie was okay, nothing special."
]

# TODO: 批量分析并打印结果
results = classifier(texts)
for text, result in zip(texts, results):
    print(f"Text: {text}")
    print(f"Sentiment: {result['label']} (confidence: {result['score']:.2f})")
    print()

练习 2: 自定义模型 (Exercise 2: Custom Model)

from transformers import pipeline

# 使用中文 BERT 模型
classifier = pipeline(
    "sentiment-analysis",
    model="bert-base-chinese"
)

# 分析中文文本
result = classifier("这个产品非常好,我很满意!")
print(result)

练习 3: Tokenizer 探索 (Exercise 3: Tokenizer Exploration)

from transformers import AutoTokenizer

# 比较不同 tokenizer
models = ["bert-base-uncased", "gpt2", "roberta-base"]

text = "Hello, world! 你好,世界!"

for model_name in models:
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    tokens = tokenizer.tokenize(text)
    print(f"{model_name}: {len(tokens)} tokens")
    print(f"  Tokens: {tokens[:10]}...")  # 显示前 10 个
    print()

📖 关键术语表 (Glossary)

English 中文 定义
Natural Language Processing 自然语言处理 AI 中处理人类语言的分支
Transformer Transformer 基于注意力的神经网络架构
Tokenizer Tokenizer 将文本转换为数字的组件
Token Token 文本的基本单位
Pipeline Pipeline 简化模型使用的 API
Pretrained model 预训练模型 在大规模数据上训练过的模型
Fine-tuning 微调 在特定任务上进一步训练
Self-attention 自注意力 序列内元素间的注意力机制
Embedding 嵌入 词的向量表示
Sequence length 序列长度 输入 token 的数量

📚 进一步学习 (Further Learning)

  1. 官方文档:
  2. Hugging Face Transformers Docs
  3. Hugging Face Course

  4. 论文:

  5. Attention Is All You Need (2017)
  6. BERT (2018)

  7. 实践项目:

  8. 情感分析项目
  9. 问答系统
  10. 文本摘要工具

下一步 (Next Steps)

完成第 1 模块后,继续学习:

  • Module 2: 使用 Hugging Face 模型
  • Module 3: 微调预训练模型
  • Module 4: 构建和共享模型
  • Module 5: 部署模型到生产

翻译完成时间: 2026-06-01
原课程模块: Module 1 (Chapter 1/1 - ⅙)
下一页: 第 2 模块 (待创建)


**Hugging Face NLP Course 中英对照 | 第 1 模块** [返回顶部](#目录-table-of-contents)