首页 > 其他分享 >transformer小白入门

transformer小白入门

时间:2023-08-20 16:11:26浏览次数:52  
标签:pipeline transformers 入门 sentiment transformer 小白 import model classifier

transformer库是huggingface发布的1个框架,非常好用,很多外行看起来高大上的问题,用它都可以轻松解决,先来看1个小例子:

 一、情感分析

from transformers import pipeline
classifier = pipeline('sentiment-analysis')
classifier('you are beautiful')

这简单的三行代码,就能分析出"you are beautiful" 这句话的情感,是积极正向的(即:好话),还是消极负面(即:坏话)。顺利的话,会看到类似下面的输出:

[{'label': 'POSITIVE', 'score': 0.9998794794082642}] 表明这是一句好话,score可以理解为可信度,0.9998即99.98%。另外注意到首次使用 sentiment-analysis 这个分类器时,会从huggingface下载依赖的模型。

万事开头难,如果你第1个示例就跑不通,出现下面的错误:

多半是transformers版本太低。可以用

import transformers
transformers.__version__

看看当前版本,如果是2.1.1就表示太低了,可另开1个终端输入:

pip install --upgrade transformers -i https://pypi.tuna.tsinghua.edu.cn/simple

将其升级至最新版本。

from transformers import pipeline
print(transformers.__version__)
classifier = pipeline('sentiment-analysis')
classifier('you are beautiful')

这次对了,如下图:

 但是有一行警告文字 :

No model was supplied, defaulted to distilbert-base-uncased-finetuned-sst-2-english and revision af0f99b (https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english).
Using a pipeline without specifying a model name and revision in production is not recommended.

 这个的意思是说,没有指定具体的模型,所以情感分析默认使用了https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english这个模型,建议指定1个具体的模型。

from transformers import pipeline
print(transformers.__version__)
model_id="distilbert-base-uncased-finetuned-sst-2-english"
classifier = pipeline('sentiment-analysis',model=model_id)
classifier('you are beautiful')

警告就被消除了。默认的模型对中文支持并不好,可以到HuggingFace上搜索"sentiment chinese",参考下图:

 可以看到很多模型,我们选下载量排行第1的这个(下图)

复制名称(参考下图)

试一下:

from transformers import pipeline
model_id="hw2942/bert-base-chinese-finetuning-financial-news-sentiment-v2"
classifier = pipeline('sentiment-analysis',model=model_id)
classifier(['这是什么鬼天气!','你可真棒!','看你那脸,拉得跟驴似的!','今天手气真差,又他妈输了!'])

模型首次使用会先下载,然后输出分析结果,可以看到,总体还算靠谱,但也有不太合理的,比如:“这是什么鬼天气!”,“看你那脸,拉得跟驴似的!” ,这二句明显是负面情绪,会被标为“中性”,所以效果好不好,主要还得看模型本身的质量。不过总体来讲,这比先前默认的英文模型,还是要强一些,来看看对比:

 

二、0样本分类

from transformers import pipeline
classifier = pipeline("zero-shot-classification")
classifier(
    "This is a course about the Transformers library",
    candidate_labels=["education", "politics", "business"],
)

效果:给一段话和几个候选标签,让代码分析每个标签匹配的可信度。以上面的例子来说,最接近education(教育)

 

三、文本生成

from transformers import pipeline
generator = pipeline("text-generation",model="distilgpt2")
generator("once upon a time", max_length=30,num_return_sequences=2)

   

四、填空

from transformers import pipeline
unmasker = pipeline("fill-mask",model="distilroberta-base")
unmasker("I love sweet foods,such as <mask>.", top_k=2)

<mask>部分将由算法自动填充

 

五、阅读理解(提取答案)

from transformers import pipeline

question_answerer = pipeline("question-answering")
question_answerer(
    question="Is it raining today?",
    context="In the evening, a large cloud drifted in the distance, and soon it began to rain"
)

 

六、翻译 

汉译英

from transformers import pipeline
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-zh-en")
translator("今天是周四,我要吃肯德基。")

英译汉

from transformers import pipeline
translator= pipeline("translation", model="Helsinki-NLP/opus-mt-en-zh")
translator("It's Thursday. I'm gonna eat Kentucky Fried Chicken.")

 

七、生成摘要

from transformers import pipeline
summarizer = pipeline("summarization",model="sshleifer/distilbart-cnn-12-6")
summarizer("""Speaking a language is a skill, like driving a car, playing a musical instrument or learning to swim. 
To be a good driver, you need to practise driving. You can read a book about car mechanics. You can study the rules of the road. 
But nothing is as good for your driving as spending time behind the wheel of a car, actually driving.
It's the same with speaking English. No matter how much you study grammar and vocabulary, if you don't practise spoken communication, it's very difficult to get good at it. 
So maybe you talk to yourself in English as you go about your day. Or maybe you look for opportunities to chat in English with people you meet. 
But however you do it, the most powerful way to improve your English speaking skills is to use them. """,max_length=100)

 

全民AI计划:快来尝试你的第一个AI程序 (baidu.com)

2

标签:pipeline,transformers,入门,sentiment,transformer,小白,import,model,classifier
From: https://www.cnblogs.com/yjmyzz/p/huggingface-transformer-pipeline-demo.html

相关文章

  • 软件测试|测试平台开发-Flask 入门:Flask HTTP请求详解
    简介上一篇文章我们介绍了flask的基本使用,编写了flask的第一个脚本。在本文中,我们将详细介绍如何使用Flask进行HTTP请求。我们将学习如何创建Flask应用程序,并通过不同的HTTP方法(GET、POST、PUT、DELETE等)发送请求。app.route()要使用不同的http方法发送请求,我们要先了解flask是如何......
  • 论文解读(CTDA)《Contrastive transformer based domain adaptation for multi-source c
    Note:[wechat:Y466551|可加勿骚扰,付费咨询]论文信息论文标题:Contrastivetransformerbaseddomainadaptationformulti-source cross-domainsentimentclassification论文作者:YanpingFu,YunLiu论文来源:2021aRxiv论文地址:download论文代码:download视屏讲解:click1......
  • c++基础入门
    1.安装g++编译器是编译C++代码使用的编译器,不要使用gcc了。在用户目录中单独创建一个文件夹存放下载后的3个安装文件,然后进入到目录中执行下面命令cd文件夹sudodpkg-i*.deb本地安装sudoapt-getinstallg++在线安装2.C++的语言特点及优势cwithclass(类)cplusplus大型......
  • Express - 入门
    创建Express应用可使用应用程序生成器工具(express-generator)快速创建应用程序框架。npminstall-gexpress-generator然后使用express命令就可以创建express应用了。express--view=pugmyapp使用这个命令创建一个myapp应用并将视图引擎将设置为pug。创建好应用后进......
  • 【Freertos基础入门】深入浅出freertos互斥量
    @TOC前言FreeRTOS是一款开源的实时操作系统,提供了许多基本的内核对象,其中包括互斥锁(Mutex)。互斥锁是一种常用的同步机制,用于确保在同一时间内只有一个任务可以访问共享资源,防止竞态条件等并发问题。本文将介绍FreeRTOS中的互斥锁的使用方法和注意事项。一、互斥量是什么?当多个任务......
  • 基础入门-算法分析&传输加密&数据格式&密文存储&代码混淆&逆向保护
    基础入门-算法分析&传输加密&数据格式&密文存储&代码混淆&逆向保护基础入门-算法分析&传输加密&数据格式&密文存储&代码混淆&逆向保护传输数据-编码型&加密型等传输格式-常规&JSON&XML等密码存储-Web&系统&三方应用代码混淆-源代码加密&逆向保护加密:1.常见加密编码进制等算法解......
  • JS入门第三节
    <ulclass="nav"><li>我的首页</li><li>产品介绍</li><li>联系方式</li></ul><script>constresult=document.querySelectorAll('li');......
  • Caddy 入门实战(3)--Caddyfile 介绍
    Caddyfile 是一种方便用户使用的Caddy配置格式。这是大多数人最喜欢使用Caddy的方式,因为它易于编写、易于理解,且能满足绝大部分的使用场景。本文主要介绍Caddyfile的相关概念。1、Caddyfile结构可选的全局选项块必须放在文件的头部否则,Caddyfile的首行总是要提供......
  • 解读HTML-入门第一文
    (HTML详细解读)概念解读HTML(HypertextMarkupLanguage)是一种用于创建网页的标记语言。作为互联网的基础,HTML在网页设计与开发中起着至关重要的作用。对于任何一个想要深入了解网页制作的人来说,掌握HTML的知识是必不可少的。本篇文章旨在帮助==小程的所有小伙伴们==更好地理解和......
  • 知识图谱入门:使用Python创建知识图,分析并训练嵌入模型
    本文中我们将解释如何构建KG、分析它以及创建嵌入模型。构建知识图谱加载我们的数据。在本文中我们将从头创建一个简单的KG。 https://avoid.overfit.cn/post/7ec9eb11e66c4b44bd2270b8ad66d80d......