提供数千种预训练模型,支持 NLP、计算机视觉、音频等多模态任务,轻松实现 SOTA 性能。
# 使用Transformers进行文本分类
from transformers import pipeline
# 创建文本分类pipeline
classifier = pipeline("text-classification")
# 分析文本情感
result = classifier("I love using Hugging Face transformers!")
print(result)
# 输出示例:
# [{'label': 'POSITIVE', 'score': 0.9998}]
Transformers库提供了简单的高级API(pipeline)和灵活的底层API,支持PyTorch和TensorFlow。
快速访问和共享数据集,支持高效的数据处理和流式加载,特别适合大规模数据集。
# 使用Datasets库加载和处理数据
from datasets import load_dataset
# 加载GLUE数据集中的MRPC任务
dataset = load_dataset("glue", "mrpc")
# 查看数据集结构
print(dataset)
# 自定义预处理函数
def preprocess(example):
example['text'] = example['sentence1'] + " [SEP] " + example['sentence2']
return example
# 应用预处理
processed_dataset = dataset.map(preprocess, batched=False)
Datasets库提供内存映射和智能缓存,即使处理超大规模数据集也不会耗尽内存。
零部署成本的机器学习应用托管平台,轻松分享你的 AI 演示给全世界。
# 创建Hugging Face Space的app.py示例
import gradio as gr
from transformers import pipeline
# 加载模型
classifier = pipeline("text-classification")
# 定义预测函数
def predict(text):
result = classifier(text)[0]
return {"label": result['label'], "score": result['score']}
# 创建Gradio界面
demo = gr.Interface(
fn=predict,
inputs=gr.Textbox(label="输入文本"),
outputs=gr.Label(label="情感分析结果"),
examples=[["I love Hugging Face!"], ["I hate this product."]]
)
# 启动应用
demo.launch()
将上述代码保存为app.py并上传到Space,Hugging Face会自动部署并提供可分享的URL。
共享和发现预训练模型,支持版本控制和社区贡献。
# 从Hub加载自定义模型
from transformers import AutoModel, AutoTokenizer
model_name = "username/my-fine-tuned-model"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)
# 将模型推送到Hub
model.push_to_hub("my-awesome-model")
tokenizer.push_to_hub("my-awesome-model")
# 使用特定版本
model = AutoModel.from_pretrained(
"bert-base-uncased",
revision="v2.0.0" # 使用特定版本
)
简化分布式训练和混合精度训练,支持多GPU/TPU。
# 使用Accelerate进行分布式训练
from accelerate import Accelerator
from transformers import AdamW
accelerator = Accelerator()
model, optimizer, train_loader = accelerator.prepare(
model, optimizer, train_loader
)
for epoch in range(epochs):
for batch in train_loader:
optimizer.zero_grad()
outputs = model(**batch)
loss = outputs.loss
accelerator.backward(loss)
optimizer.step()
# 保存模型
accelerator.wait_for_everyone()
unwrapped_model = accelerator.unwrap_model(model)
unwrapped_model.save_pretrained("my-model")
无需部署即可通过API调用数千个预训练模型。
# 使用Hugging Face Inference API
import requests
API_URL = "https://api-inference.huggingface.co/models/bert-base-uncased"
headers = {"Authorization": "Bearer YOUR_API_TOKEN"}
def query(payload):
response = requests.post(API_URL, headers=headers, json=payload)
return response.json()
output = query({
"inputs": "The answer to the universe is [MASK]."
})
# 输出:
# [{'sequence': 'the answer to the universe is life.',
# 'score': 0.109...}]
无需自己部署模型,直接通过HTTP请求调用Hugging Face托管的模型。
文本分类是NLP中最常见的任务之一,下面展示如何使用Hugging Face的pipeline快速实现。
from transformers import pipeline
# 创建文本分类pipeline
classifier = pipeline("text-classification")
# 分析文本情感
result = classifier("Hugging Face makes NLP so easy and fun!")
print(result)
# 输出示例:
# [{'label': 'POSITIVE', 'score': 0.9998}]
提示: 你可以通过指定model参数来使用不同的预训练模型,例如:
model="distilbert-base-uncased-finetuned-sst-2-english"
使用Hugging Face的pipeline可以轻松构建一个基于上下文的问答系统。
from transformers import pipeline
# 创建问答pipeline
qa_pipeline = pipeline("question-answering")
# 定义上下文和问题
context = "Hugging Face is a company based in New York and Paris. " +
"It provides state-of-the-art NLP models."
question = "Where is Hugging Face based?"
# 获取答案
result = qa_pipeline(question=question, context=context)
print(result)
# 输出示例:
# {'answer': 'New York and Paris', 'score': 0.918...}
注意: 问答系统需要提供上下文信息,模型会从中提取最相关的答案。
使用GPT风格的模型进行文本生成是Hugging Face的另一个强大功能。
from transformers import pipeline
# 创建文本生成pipeline
generator = pipeline("text-generation", model="gpt2")
# 生成文本
result = generator(
"In the future, AI will",
max_length=50,
num_return_sequences=2
)
for i, seq in enumerate(result):
print(f"结果 {i+1}: {seq['generated_text']}\n")
# 输出示例:
# 结果 1: In the future, AI will be able to understand and respond to human emotions...
# 结果 2: In the future, AI will have surpassed human intelligence in many domains...
参数说明: 你可以调整max_length控制生成长度,num_return_sequences控制返回结果数量。
输入一段文本,体验Hugging Face的情感分析模型。