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模型库,支持按任务类型筛选。

相关推荐
lpfasd1232 小时前
2026年第30周科技社区趋势周报:开放权重之争与AI Agent的破局
人工智能·科技
佛光芳林3 小时前
AI 情报局:用 PowerMem + SeekDB 做一个多 Agent 记忆小游戏
人工智能
通问AI4 小时前
2026年AI短剧技术现状:全链路AIGC生产已达95%,但用户完播率不足15%
人工智能·aigc
_Jimmy_4 小时前
Agent引用数据库知识过时的增量同步方案
人工智能·python·langchain
qq_454245034 小时前
Systemprompt 体系全览:形式化公理驱动的分层系统设计
人工智能
大龄码农有梦想4 小时前
传统的 BPMN 工作流审批和 AI 工作流有什么区别?
人工智能·流程引擎·工作流·ai agent·ai工作流·审批流·智能体平台
DO_Community4 小时前
Claude Opus 5 现已上线 DigitalOcean AI 推理云
人工智能·llm·agent·claude
幸福指北4 小时前
🚀 开源了,一个人 + AI 肝出一个 AI 终端 | AShell 技术分享
运维·人工智能·ai·终端
可以飞的话4 小时前
一、机器学习概述
人工智能·机器学习
sunneo4 小时前
磐石2.0发布,科学建模新突破
人工智能