Hugging Face Transformers 上手教程
从零安装到跑通文本分类与文本生成,预计 25 分钟
前置准备
- Python:3.9 及以上(推荐 3.10/3.11)。
- 深度学习框架:PyTorch 2.0+(本教程以 PyTorch 为例),TensorFlow/JAX 用户可安装对应版本。
- 包管理:pip 23+,建议使用虚拟环境(venv 或 conda)避免依赖冲突。
- 网络:首次使用需从 Hugging Face Hub 下载模型,确保可访问
huggingface.co;国内网络可使用镜像HF_ENDPOINT=https://hf-mirror.com。 - 硬件:CPU 可跑通全部示例(小模型);GPU(推荐 8GB+ 显存)可显著加速,微调大模型需更大显存。
- 磁盘:预留 2–5 GB 空间用于缓存模型权重。
安装与配置
方式一:pip 安装(推荐)
# 创建并激活虚拟环境(Windows 用 .venv\Scripts\activate)
python -m venv .venv
source .venv/bin/activate
# 安装 PyTorch(CPU 版本;GPU 版本见 pytorch.org 按 CUDA 版本选择)
pip install torch --index-url https://download.pytorch.org/whl/cpu
# 安装 Transformers 及常用依赖
pip install "transformers[torch]" accelerate datasets sentencepiece
方式二:conda 安装
conda create -n hf python=3.10 -y
conda activate hf
conda install pytorch cpuonly -c pytorch
conda install -c huggingface transformers datasets accelerate
配置国内镜像(可选)
# Linux / macOS
export HF_ENDPOINT=https://hf-mirror.com
# Windows PowerShell
# $env:HF_ENDPOINT="https://hf-mirror.com"
验证安装
python -c "import transformers; print(transformers.__version__)"
输出版本号(如 4.44.2)即安装成功。
快速开始:第一个示例
使用 pipeline 完成零样本情感分析,无需任何训练代码:
# quickstart.py
from transformers import pipeline
# 指定任务名,pipeline 会自动下载并加载默认模型
classifier = pipeline("sentiment-analysis")
result = classifier("I've been waiting for a HuggingFace course my whole life.")
print(result)
首次运行会下载模型(约 250 MB),预期输出:
[{'label': 'POSITIVE', 'score': 0.9598}]
再试一个负例:
print(classifier("This movie was terrible and boring."))
# [{'label': 'NEGATIVE', 'score': 0.9981}]
说明:指定具体模型可复现结果,例如 pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")。
核心操作详解
1. 手动加载模型与分词器(理解底层流程)
pipeline 是高层封装,手动调用能看清"分词 → 模型推理 → 后处理"三步:
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
model_name = "distilbert-base-uncased-finetuned-sst-2-english"
# AutoTokenizer / AutoModelForSequenceClassification 按模型名自动选择对应类
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)
# 1) 分词:return_tensors="pt" 返回 PyTorch 张量;padding/truncation 统一长度
inputs = tokenizer(
["I love this!", "I hate this."],
padding=True,
truncation=True,
max_length=128,
return_tensors="pt",
)
# 2) 推理:no_grad 关闭梯度计算,加快速度
with torch.no_grad():
outputs = model(**inputs)
# 3) 后处理:logits → 概率 → 类别
probs = torch.softmax(outputs.logits, dim=-1)
id2label = model.config.id2label
for prob in probs:
print(id2label[prob.argmax().item()], round(prob.max().item(), 4))
2. 文本生成(GPT 系列)
from transformers import AutoTokenizer, AutoModelForCausalLM
model_name = "gpt2" # 也可换成 "Qwen/Qwen2.5-0.5B" 等
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
inputs = tokenizer("The future of AI is", return_tensors="pt")
outputs = model.generate(
**inputs,
max_new_tokens=50, # 最多生成 50 个新 token
do_sample=True, # 启用采样,输出更有多样性
temperature=0.7, # 控制随机性:越低越确定
top_p=0.9, # 核采样阈值
pad_token_id=tokenizer.eos_token_id,
)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
3. 使用 Trainer 微调文本分类模型
以下用 GLUE 的 SST-2 子集演示完整微调流程(可在本机 CPU 上跑通,GPU 更快):
from datasets import load_dataset
from transformers import (
AutoTokenizer,
AutoModelForSequenceClassification,
TrainingArguments,
Trainer,
)
import numpy as np
import evaluate
model_name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
# 加载数据集(仅取小样本加快演示)
dataset = load_dataset("glue", "sst2")
small_train = dataset["train"].shuffle(seed=42).select(range(1000))
small_eval = dataset["validation"].shuffle(seed=42).select(range(200))
def tokenize_fn(examples):
return tokenizer(examples["sentence"], truncation=True, max_length=128)
encoded_train = small_train.map(tokenize_fn, batched=True)
encoded_eval = small_eval.map(tokenize_fn, batched=True)
model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2)
accuracy = evaluate.load("accuracy")
def compute_metrics(eval_pred):
logits, labels = eval_pred
return accuracy.compute(predictions=np.argmax(logits, axis=-1), references=labels)
training_args = TrainingArguments(
output_dir="./sst2-finetuned",
eval_strategy="epoch",
save_strategy="epoch",
per_device_train_batch_size=16,
per_device_eval_batch_size=16,
num_train_epochs=3,
learning_rate=2e-5,
load_best_model_at_end=True,
metric_for_best_model="accuracy",
logging_steps=20,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=encoded_train,
eval_dataset=encoded_eval,
compute_metrics=compute_metrics,
processing_class=tokenizer,
)
trainer.train()
print(trainer.evaluate())
新版 Transformers(4.46+)用 eval_strategy 并推荐 processing_class 传分词器;旧版对应参数为 evaluation_strategy 和 tokenizer。
4. 保存与重新加载微调后的模型
trainer.save_model("./my-sentiment-model") # 保存到本地目录
tokenizer.save_pretrained("./my-sentiment-model")
# 之后随时重新加载
from transformers import pipeline
clf = pipeline("sentiment-analysis", model="./my-sentiment-model")
print(clf("What a wonderful day!"))
5. 上传到 Hub 与从 Hub 加载(进阶)
# 需先 huggingface-cli login 登录
trainer.push_to_hub("my-sentiment-model") # 上传模型
# 任何人可用仓库名加载
clf = pipeline("sentiment-analysis", model="你的用户名/my-sentiment-model")
典型实战案例
案例:搭建一个批量情感分析脚本,处理 CSV 评论数据
需求:读取 reviews.csv(含 text 列),批量输出每条评论的情感与置信度,结果写回 result.csv。
# batch_sentiment.py
import pandas as pd
from transformers import pipeline
# 批处理:batch_size 提升吞吐,device=0 表示使用第一块 GPU(CPU 用 device=-1)
classifier = pipeline(
"sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english",
device=-1,
)
df = pd.read_csv("reviews.csv")
texts = df["text"].astype(str).tolist()
# truncation=True 防止长文本超出模型最大长度(512 token)
results = classifier(texts, batch_size=32, truncation=True)
df["label"] = [r["label"] for r in results]
df["score"] = [round(r["score"], 4) for r in results]
df.to_csv("result.csv", index=False)
print(df[["text", "label", "score"]].head(10))
print(f"处理完成,共 {len(df)} 条评论,结果已保存到 result.csv")
运行:
pip install pandas
python batch_sentiment.py
要点:长文本必须 truncation=True,否则报错;batch_size 在 GPU 上可调至 32–128,CPU 建议 8–16;模型只加载一次,避免循环内重复初始化。
常见问题与排错
Q1:下载模型时卡住或报网络错误?
A:设置镜像 export HF_ENDPOINT=https://hf-mirror.com;或手动下载模型文件到本地目录后用 from_pretrained("./本地目录") 加载。首次下载后文件缓存在 ~/.cache/huggingface/hub,后续离线可用。
Q2:报 CUDA out of memory(显存不足)?
A:减小 per_device_train_batch_size 或 batch_size;启用梯度累积(gradient_accumulation_steps=2);推理时使用 model.half() 半精度,或换用更小的模型(如 distilbert)。
Q3:输入文本过长报 token 索引越界?
A:分词时加 truncation=True, max_length=模型最大长度(BERT 类为 512);pipeline 中同样传 truncation=True。
Q4:AutoModelForSequenceClassification 加载模型时提示权重未初始化?
A:当 checkpoint 与自定义 num_labels 不一致时,分类头会随机初始化并给出警告,属正常现象,微调后会被训练。若只是做推理,应下载已微调好的模型。
Q5:CPU 上训练太慢怎么办?
A:演示用小数据集 + 小模型(distilbert);正式训练使用 GPU,并配合 fp16=True(Trainer 参数,需 NVIDIA GPU)与 Accelerate 多卡扩展。
进阶学习资源
- 官方文档:https://huggingface.co/docs/transformers (API 参考+任务指南)
- 官方课程:https://huggingface.co/learn/nlp-course (免费,从分词到微调系统讲解)
- Hugging Face Hub:https://huggingface.co/models (搜索、试用任意模型)
- Accelerate:https://huggingface.co/docs/accelerate (分布式训练)
- PEFT / LoRA:https://huggingface.co/docs/peft (低成本微调大模型)
- 社区:https://discuss.huggingface.co (官方论坛)、GitHub Discussions 与 Discord