当前位置: 首页 > news >正文

huggingface 笔记:pipeline

1 介绍 

  • pipeline() 是使用预训练模型进行推理的最简单和最快速的方式。
  • 可以针对不同模态的许多任务直接使用 pipeline()

2 举例:情感分析

2.1 创建pipeline实例

from transformers import pipelineclassifier = pipeline("sentiment-analysis")
#首先创建一个 pipeline() 实例,并指定您想要使用它的任务
#pipeline() 将下载并缓存情感分析的默认预训练模型和分词器

2.2 使用pipeline实例 

然后就可以在目标文本上使用分类器了:

# 单个文本
classifier('Today is a shiny day!')
'''
[{'label': 'POSITIVE', 'score': 0.9992596507072449}]
'''
# 多个文本
classifier(['Today is a shiny day!','What a bad day it is!'])
'''
[{'label': 'POSITIVE', 'score': 0.9992596507072449},{'label': 'NEGATIVE', 'score': 0.999808132648468}]
'''

3 使用别的模型和分词器

  • pipeline() 可以容纳来自 Models - Hugging Face的任何模型
  • eg:能够处理法语文本的模型

以下两种方式都可以

from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers import pipelinemodel_name = "nlptown/bert-base-multilingual-uncased-sentiment"classifier = pipeline("sentiment-analysis", model=model_name)classifier("Nous sommes très heureux de vous présenter la bibliothèque Transformers.")#[{'label': '5 stars', 'score': 0.7236300706863403}]
from transformers import AutoTokenizer, AutoModelForSequenceClassificationmodel_name = "nlptown/bert-base-multilingual-uncased-sentiment"model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)classifier("Nous sommes très heureux de vous présenter la bibliothèque Transformers.")
#[{'label': '5 stars', 'score': 0.7236300706863403}]

4 device相关

  • 使用 device=n——>pipeline会自动将模型放置在指定的设备上
classifier = pipeline("sentiment-analysis", model=model_name,device=2)
  • 如果模型对于单个 GPU 来说太大,并且使用 PyTorch——>可以设置 device_map="auto",以自动确定如何加载和存储模型权重
classifier = pipeline("sentiment-analysis", model=model_name,device_map="auto")
  • 如果传递了 device_map="auto",在实例化pipeline时不需要添加参数 device=device
http://www.lryc.cn/news/349591.html

相关文章:

  • 玩转Matlab-Simscape(初级)-01-从一个简单模型开始学习之旅
  • 电脑录屏软件有哪些?这3款神器必须要知道
  • 如何在华企盾DSC防泄密系统中设置文件自动加密?
  • 【DevOps】Dockerfile详解,做自己的docker镜像
  • CSRF 攻击实验:Token 不存在绕过验证
  • c#教程——索引器
  • 麒麟服务器上执行可执行脚本报错:bash: ./xx: Permission denied(完整版)
  • 触觉美学:移动端UI设计的视觉盛宴
  • 前端起dev从110秒减少到7秒, 开发体验大幅提升
  • Flink CDC 原理
  • Axure网上超市用户端APP原型 (O2O生鲜电商/买菜到家/数字零售/京东到家/抖音超市领域)
  • 外包公司中能学到技术的都是那些人?
  • JavaEE初阶-多线程进阶2
  • B/S和C/S框架
  • 机器学习中常用的几种距离——欧式、余弦等
  • 2024 Google I/O Android 相关内容汇总
  • # 从浅入深 学习 SpringCloud 微服务架构(十八)
  • 在SQL Server中使用临时表与普通表的性能差异分析
  • 数据中台管理系统原型
  • 数据库练习
  • Rust学习笔记(上)
  • 【SRC实战】文件名回显导致反射型XSS,URL重定向
  • mysql高版本导入低版本Unknown collation: utf8mb4_0900_ai_ci
  • 运筹说 第114期 | 其他排队模型简介
  • 易基因: WGBS等揭示梨驯化和改良过程中DNA甲基化对果实成熟的作用机制 | 作物育种
  • 数据分析(二)——导入外部数据,导入Excel数据,CSV文件,txt文件,HTML网页,数据抽取,DataFrame对象的loc属性与iloc属性
  • 如何让Linux系统崩溃?
  • C# 实现邮件推送功能
  • 企业微信私域营销:构建高效转化新引擎
  • 电力物联网-(2)系统设计