Hugging Face Transformers快速上手

Hugging Face Transformers快速入门指南

Hugging Face Transformers库提供了预训练模型和简单API,支持自然语言处理(NLP)任务的快速实现。以下是核心使用方法:

安装环境

bash 复制代码
pip install transformers
pip install torch  # 推荐安装PyTorch作为后端

加载预训练模型

python 复制代码
from transformers import AutoTokenizer, AutoModelForSequenceClassification

model_name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)

文本预处理

python 复制代码
text = "Hugging Face makes NLP easy."
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)

模型推理

python 复制代码
outputs = model(**inputs)
predictions = outputs.logits.argmax(-1)

保存与加载模型

python 复制代码
model.save_pretrained("./saved_model")
tokenizer.save_pretrained("./saved_model")

# 加载时
model = AutoModelForSequenceClassification.from_pretrained("./saved_model")

常见任务示例

  • 文本分类:使用bert-base-uncased等模型
  • 问答系统:尝试distilbert-base-cased-distilled-squad
  • 文本生成:选择gpt2facebook/opt-350m

使用Pipeline快速推理

python 复制代码
from transformers import pipeline

classifier = pipeline("sentiment-analysis")
result = classifier("I love using Hugging Face!")

注意事项

  • 首次运行会自动下载模型至~/.cache/huggingface
  • 大模型需注意GPU显存限制
  • 可指定device_map="auto"自动分配计算设备

最新模型列表可查阅Hugging Face模型库,支持按任务类型筛选。

相关推荐
艺杯羹6 分钟前
古典密码学攻防演进全景:从凯撒移位、频率分析到一次一密与恩尼格玛机破译
网络·人工智能·安全·网络安全·密码学·密码安全
灰灰20268 分钟前
我的 AI 工作流:多模型组队,IMA知识库做底座
人工智能
盗理者15 分钟前
AI Agent 工程实践|让 AI Agent 自动修 Bug:定位、修改、测试与人工审核
人工智能·bug·agent
katttt_32 分钟前
实体经营,优先选卡特加特垂域专用AI
人工智能·卡特加特
阿里云大数据AI技术36 分钟前
EMR Daft × Qoder:一句话生成并运行智驾数据处理 Pipeline
人工智能
OceanBase数据库官方博客1 小时前
OceanBase Harness Engineering?AI 产品真正的瓶(技术解析与实践)
大数据·人工智能·oceanbase
兰亭妙微UI设计公司1 小时前
兰亭妙微 UX 实战:新手引导全类型设计入门指南
人工智能·ux
阿标在干嘛1 小时前
3种主流NLP模型在招标信息匹配中的效果实测
人工智能·自然语言处理
手写码匠1 小时前
华为云Flexus+DeepSeek征文|Dify 多 Agent 故障演练实战:用混沌工程主动“搞破坏“,让智能体系统越炸越稳
人工智能·深度学习·算法·aigc
Summer-Bright1 小时前
[马斯克600亿买下Cursor] —— AI 应用简报 08.13-08.17
人工智能·ai·ai应用·马斯克