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
  • 文本生成:选择gpt2或facebook/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模型库,支持按任务类型筛选。

相关推荐
fly-iot1 小时前
【摩尔线程S4000卡】执行Qwen3-14B-W8A8 量化、启动与接口性能测试报告,结果更慢了13 tok/s
人工智能·语言模型
budingxiaomoli1 小时前
LangChain与LangGraph介绍
人工智能·langchain
龙腾AI白云1 小时前
触觉预测与接触动力学:具身智能摸懂世界的底层机制
大数据·人工智能·机器学习·知识图谱·pygame
鲁邦通物联网2 小时前
机器人梯控多机调度设计:请求队列、资源分配与状态反馈
人工智能·机器人·巡检机器人·机器人梯控·agv梯控·非侵入式采集·机器人乘梯
VIP_CQCRE2 小时前
GPT Image 2.6 编辑把红圈也画进成品?标注图分工与残留验收教程
图像处理·人工智能·aigc
Regulus-Moon2 小时前
人工智能数学基础:矩阵特征分解与压缩实战
人工智能·线性代数·矩阵
qyr67893 小时前
安全载荷指示器:市场发展现状与未来发展前景趋势分析
大数据·人工智能·安全·自动化·安全载荷指示器
Dawson Zhu3 小时前
Agent记忆架构深度解析:为什么摘要会丢信息?如何构建“无损优先“的记忆系统
人工智能·语言模型·架构·aigc·agi
迦蓝叶3 小时前
自建 MaaS 卡住的地方从来不是模型:JAiRouter 开源 AI 网关的四个答案
人工智能·spring boot·开源·架构设计·maas·ai 网关
测试员周周3 小时前
【AI提效】UI自动化页面截图像成功了,业务结果却没有。到底该提缺陷,还是该骂脚本?
人工智能