Hugging Face Transformers?是一個基于?PyTorch?和?TensorFlow?的開源庫,專注于?最先進的自然語言處理(NLP)模型,如?BERT、GPT、RoBERTa、T5?等。它提供了?預訓練模型、微調工具和推理 API,廣泛應用于文本分類、機器翻譯、問答系統等任務。
1. Hugging Face Transformers 的特點
??豐富的預訓練模型:支持?500+ 種模型(如 BERT、GPT-3、Llama 2)。
??跨框架支持:兼容?PyTorch、TensorFlow、JAX。
??易用 API:提供?pipeline
,幾行代碼即可實現 NLP 任務。
??社區支持:Hugging Face Hub 提供?數千個公開模型和數據集。
??支持自定義訓練:可微調(Fine-tune)模型以適應特定任務。
2. 主要功能
(1) 開箱即用的 NLP 任務
-
文本分類(情感分析、垃圾郵件檢測)
-
命名實體識別(NER)
-
問答系統(QA)
-
文本生成(如 GPT-3、Llama 2)
-
機器翻譯
-
摘要生成
(2) 核心組件
-
pipeline
:快速調用預訓練模型進行推理。 -
AutoModel
?/?AutoTokenizer
:自動加載模型和分詞器。 -
Trainer
:簡化模型訓練和微調流程。 -
Datasets
:高效加載和處理數據集。
3. 安裝與基本使用
(1) 安裝
pip install transformers
(可選)安裝 PyTorch / TensorFlow:
pip install torch # PyTorch
pip install tensorflow # TensorFlow
注:此處我嘗試了安裝gpu版本的,因為我電腦安裝的cuda版本較低,所以試了幾個版本的tensorflow-gpu版本都和transformer版本不匹配。
(2) 使用?pipeline
?快速體驗
from transformers import pipeline
# 情感分析 將下載的模型存于multilingual-sentiment-analysis路徑下
classifier=pipeline("text-classification",model="./multilingual-sentiment-analysis")
print(classifier("我很驕傲"))
# 文本生成
# 指定本地路徑加載模型,將下載的模型存于gpt2路徑下
generator = pipeline("text-generation",model="./gpt2")# 本地模型路徑
result=generator("AI will change",max_length=50)
print(result[0]['generated_text'])
因為模型在線下載會比較麻煩,建議離線下載好,放到指定的文件夾下,方便調用
通過網盤分享的文件:gpt2
鏈接: https://pan.baidu.com/s/1Z9MZQKyOQrLlvn_jh3bGOg 提取碼: 8ihe
通過網盤分享的文件:multilingual-sentiment-analysis
鏈接: https://pan.baidu.com/s/16e6Jvo44vetMmTxrQcZZqQ 提取碼: tv4e
(3) 加載自定義模型
from transformers import AutoTokenizer, AutoModelForSequenceClassification# 加載模型和分詞器
model_name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)# 處理輸入
inputs = tokenizer("Hello, world!", return_tensors="pt")
outputs = model(**inputs)
print(outputs)
4. 常用預訓練模型
模型 | 用途 | 示例模型 ID |
---|---|---|
BERT | 文本分類、NER、問答 | bert-base-uncased |
GPT-2 | 文本生成 | gpt2 |
T5 | 文本摘要、翻譯 | t5-small |
RoBERTa | 更強大的 BERT 變體 | roberta-base |
Llama 2 | Meta 開源的大語言模型 | meta-llama/Llama-2-7b |
5. 與 spaCy 的比較
特性 | Hugging Face Transformers | spaCy |
---|---|---|
模型類型 | 深度學習(BERT、GPT) | 傳統統計模型 + 部分 DL |
速度 | 較慢(依賴 GPU 加速) | ? 極快(CPU 友好) |
適用任務 | 復雜 NLP(翻譯、生成) | 基礎 NLP(分詞、NER) |
自定義訓練 | ? 支持(微調 LLM) | ? 支持(但規模較小) |
易用性 | 中等(需了解深度學習) | 👍 非常簡單 |
👉?推薦選擇:
-
如果需要?最先進的 NLP(如 ChatGPT 類應用)?→?Hugging Face。
-
如果需要?快速處理結構化文本(如實體提取)?→?spaCy。
6. 實戰案例
(1) 聊天機器人(使用 GPT-2)
from transformers import pipeline
chatbot = pipeline("text-generation", model="./gpt2")
response = chatbot("What is the future of AI?", max_length=50)
print(response[0]['generated_text'])
(2) 自定義微調(Fine-tuning)
from transformers import Trainer, TrainingArgumentstraining_args = TrainingArguments(output_dir="./results",per_device_train_batch_size=8,num_train_epochs=3,
)trainer = Trainer(model=model,args=training_args,train_dataset=train_dataset,eval_dataset=eval_dataset,
)
trainer.train()
(3)情感分析
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
model_name = "./multilingual-sentiment-analysis"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)def predict_sentiment(texts):inputs = tokenizer(texts, return_tensors="pt", truncation=True, padding=True, max_length=512)with torch.no_grad():outputs = model(**inputs)probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)sentiment_map = {0: "Very Negative", 1: "Negative", 2: "Neutral", 3: "Positive", 4: "Very Positive"}return [sentiment_map[p] for p in torch.argmax(probabilities, dim=-1).tolist()]texts = [# English"I absolutely love the new design of this app!", "The customer service was disappointing.", "The weather is fine, nothing special.",# Chinese"這家餐廳的菜味道非常棒!", "我對他的回答很失望。", "天氣今天一般。",# Spanish"?Me encanta cómo quedó la decoración!", "El servicio fue terrible y muy lento.", "El libro estuvo más o menos.",# Arabic"?????? ?? ??? ?????? ????? ????!", "?? ?????? ?????? ?? ??? ??????.", "???? ?????? ?????。",# Ukrainian"Мен? дуже сподобалася ця вистава!", "Обслуговування було жахливим.", "Книга була посередньою。",# Hindi"?? ??? ?? ??? ?????? ??!", "?? ????? ???? ???? ???", "????? ???-??? ???",# Bengali"??????? ?????? ???????!", "????? ??? ???????? ??????", "??????? ???????? ????",# Portuguese"Este livro é fantástico! Eu aprendi muitas coisas novas e inspiradoras.","N?o gostei do produto, veio quebrado.", "O filme foi ok, nada de especial.",# Japanese"このレストランの料理は本當に美味しいです!", "このホテルのサービスはがっかりしました。", "天気はまあまあです。",# Russian"Я в восторге от этого нового гаджета!", "Этот сервис оставил у меня только разочарование.", "Встреча была обычной, ничего особенного.",# French"J'adore ce restaurant, c'est excellent !", "L'attente était trop longue et frustrante.", "Le film était moyen, sans plus.",# Turkish"Bu otelin manzaras?na bay?ld?m!", "ürün tam bir hayal k?r?kl???yd?.", "Konser fena de?ildi, ortalamayd?.",# Italian"Adoro questo posto, è fantastico!", "Il servizio clienti è stato pessimo.", "La cena era nella media.",# Polish"Uwielbiam t? restauracj?, jedzenie jest ?wietne!", "Obs?uga klienta by?a rozczarowuj?ca.", "Pogoda jest w porz?dku, nic szczególnego.",# Tagalog"Ang ganda ng lugar na ito, sobrang aliwalas!", "Hindi maganda ang serbisyo nila dito.", "Maayos lang ang palabas, walang espesyal.",# Dutch"Ik ben echt blij met mijn nieuwe aankoop!", "De klantenservice was echt slecht.", "De presentatie was gewoon oké, niet bijzonder.",# Malay"Saya suka makanan di sini, sangat sedap!", "Pengalaman ini sangat mengecewakan.", "Hari ini cuacanya biasa sahaja.",# Korean"? ??? ???? ?? ????!", "???? ?? ?????.", "??? ?? ????.",# Swiss German"Ich find d? Service i de Beiz mega guet!", "D?s Es? het mir n?d gfalle.", "D W?tter hüt isch so naja."
]for text, sentiment in zip(texts, predict_sentiment(texts)):print(f"Text: {text}\nSentiment: {sentiment}\n")
7. 學習資源
-
官方文檔:?huggingface.co/docs/transformers
-
Hugging Face 課程:?huggingface.co/course(免費 NLP 課程)
-
模型庫:?huggingface.co/models
總結
Hugging Face Transformers 是?當今最強大的 NLP 庫之一,適用于:
-
前沿 AI 研究(如 LLM、ChatGPT 類應用)
-
企業級 NLP 解決方案(如智能客服、自動摘要)
-
快速實驗 SOTA 模型
🚀?推薦下一步:
-
嘗試?
pipeline()
?運行不同任務(如?"text-generation"
)。 -
在?Hugging Face Hub?上探索開源模型(如?
bert-base-uncased
)。 -
學習?微調(Fine-tuning)?以適應自定義數據集。