跳转至

Hugging Face Transformers

一句话概述:Hugging Face Transformers 是最大的预训练模型库,提供 100,000+ 模型(BERT、GPT、LLaMA 等),几行代码就能做文本分类、翻译、问答、文本生成,是 NLP/AI 开发的事实标准。Transformers v5(2026)PyTorch 优先。

核心知识点

概念白话解释
Transformer变换器 = 基于注意力机制的模型架构
Pipeline管道 = 一行代码完成推理(最简单的使用方式)
Tokenizer分词器 = 把文本切成模型能理解的 token
Model Hub模型中心 = huggingface.co 上的模型仓库
Fine-tuning微调 = 在预训练模型上用自己的数据继续训练
AutoClass自动类 = 自动选择正确的模型/分词器

安装配置

pip install transformers torch                        # 安装(PyTorch 后端)
pip install accelerate                                # 多 GPU / 混合精度训练
pip install datasets                                  # 数据集库

基本使用

Pipeline(最简单)

from transformers import pipeline                     # 导入管道

# 情感分析
classifier = pipeline("sentiment-analysis")           # 加载模型
result = classifier("I love this product!")           # 推理
print(result)  # [{'label': 'POSITIVE', 'score': 0.9998}]

# 文本生成
generator = pipeline("text-generation", model="gpt2") # GPT-2
text = generator("The future of AI is", max_length=50)
print(text[0]['generated_text'])

# 中文情感分析
classifier_zh = pipeline("sentiment-analysis",
                          model="uer/roberta-base-finetuned-chinanews-chinese")
print(classifier_zh("这个产品非常好用"))

# 零样本分类(不需要训练数据!)
zero_shot = pipeline("zero-shot-classification")
result = zero_shot(
    "这篇论文研究了肠道菌群与糖尿病的关系",
    candidate_labels=["医学", "计算机", "金融"]        # 候选标签
)
print(result['labels'][0])  # 医学

# 问答
qa = pipeline("question-answering")
result = qa(
    question="What is the capital of France?",
    context="France is a country in Europe. Its capital is Paris."
)
print(result['answer'])  # Paris

AutoClass(更灵活)

from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch

# 加载模型和分词器
model_name = "bert-base-uncased"                      # 模型名
tokenizer = AutoTokenizer.from_pretrained(model_name) # 分词器
model = AutoModelForSequenceClassification.from_pretrained(
    model_name, num_labels=2                          # 2 分类
)

# 分词
inputs = tokenizer(
    "I love bioinformatics!",                         # 输入文本
    return_tensors="pt",                              # 返回 PyTorch 张量
    padding=True,                                     # 填充
    truncation=True,                                  # 截断
    max_length=128                                    # 最大长度
)

# 推理
model.eval()
with torch.no_grad():
    outputs = model(**inputs)                         # 前向传播
    logits = outputs.logits                           # 输出 logits
    predicted = torch.argmax(logits, dim=1)           # 预测类别
    print(f"预测: {predicted.item()}")

高级用法

微调训练

from transformers import Trainer, TrainingArguments   # 训练器
from datasets import load_dataset                     # 数据集

# 加载数据集
dataset = load_dataset("imdb")                        # IMDB 情感数据集

# 分词函数
def tokenize_fn(examples):
    return tokenizer(examples["text"], padding="max_length",
                     truncation=True, max_length=256)

tokenized = dataset.map(tokenize_fn, batched=True)    # 批量分词

# 训练配置
training_args = TrainingArguments(
    output_dir="./results",                           # 输出目录
    num_train_epochs=3,                               # 训练轮数
    per_device_train_batch_size=16,                   # 批次大小
    per_device_eval_batch_size=64,                    # 评估批次
    learning_rate=2e-5,                               # 学习率
    eval_strategy="epoch",                            # 每轮评估
    save_strategy="epoch",                            # 每轮保存
    load_best_model_at_end=True,                      # 最后加载最优
)

# 创建训练器
trainer = Trainer(
    model=model,                                      # 模型
    args=training_args,                               # 训练参数
    train_dataset=tokenized["train"],                 # 训练集
    eval_dataset=tokenized["test"],                   # 测试集
)

# 训练
trainer.train()                                       # 开始训练
trainer.save_model("./best_model")                    # 保存最优模型

常见报错

报错信息原因解决方法
OSError: Can't load model模型名错误或网络问题检查模型名或下载到本地
CUDA out of memoryGPU 内存不足减小 batch_size 或用 fp16=True
Token indices sequence length输入超过最大长度添加 truncation=True

速查表

# === Pipeline 任务 ===
pipeline("sentiment-analysis")         # 情感分析
pipeline("text-generation")            # 文本生成
pipeline("question-answering")         # 问答
pipeline("summarization")             # 摘要
pipeline("translation_en_to_zh")      # 翻译
pipeline("zero-shot-classification")   # 零样本分类
pipeline("fill-mask")                  # 完形填空
pipeline("token-classification")       # 命名实体识别

# === 核心流程 ===
# 1. 选择模型(huggingface.co)
# 2. AutoTokenizer.from_pretrained()  → 分词器
# 3. AutoModel.from_pretrained()      → 模型
# 4. tokenizer(text)                  → 分词
# 5. model(**inputs)                  → 推理
# 6. Trainer + TrainingArguments      → 微调

# === 热门模型 ===
# BERT: bert-base-uncased(理解型)
# GPT-2: gpt2(生成型)
# RoBERTa: roberta-base(增强 BERT)
# T5: t5-base(文本到文本)
# LLaMA: meta-llama/(开源大模型)

参考:Hugging Face | Transformers 文档 | v5 (2026) | 更新于 2026 年