诸神缄默不语-个人CSDN博文目录

本文属于huggingface.transformers全部文档学习笔记博文的一部分。
全文链接:huggingface transformers包 文档学习笔记(持续更新ing…)

本部分网址:https://huggingface.co/docs/transformers/master/en/task_summary
本部分介绍了一些常见NLP任务使用transformers包的解决方案。本文使用的AutoModel具体内容可以参阅其文档,也可以参考我此前的撰写的transformers包文档笔记,我介绍了一些相关的用法和示例代码。

文章目录

  • 1. Sequence Classification
  • 2. Extractive Question Answering
  • 3. Language Modeling
    • 3.1 Masked Language Modeling
    • 3.2 Causal Language Modeling
    • 3.3 Text Generation
  • 4. Named Entity Recognition
  • 5. Summarization
  • 6. Translation

模型需要从针对对应任务上预训练过的checkpoint加载,才能更好地应用于对应任务。(如果加载的是未经过特定任务微调的checkpoint会仅加载基础transformers层,没有特定任务所需的additional head,就会随机初始化additional head权重,产生随机输出)
这些checkpoints往往是在大量语料上预训练(pre-train),然后再针对具体任务进行微调(fine-tune)过。这意味着:

  1. 不是所有模型都在所有任务上微调过。如果用户想针对某一任务对模型进行微调,可以参考使用transformers官方GitHub项目中的examples文件夹中的代码:transformers/examples at master · huggingface/transformers 关于这个的笔记我已经列在卫星里面了:接下来博文写作计划的卫星 以后会写的,所以本文不会讲这些代码
  2. checkpoints是在特定数据集上被微调过的,该数据集可能无法覆盖用户自己的用例和领域。如前所述,用户可以自己再继续微调。

如果想在指定任务上直接做推理,可以使用这些机制:

  1. Pipelines:很容易用的抽象,两行代码即可实现。对pipeline的使用,更详细的笔记可参考我之前撰写的博文:huggingface.transformers速成笔记:Pipeline推理和AutoClass第一节。
  2. 直接使用模型:抽象程度较低,但更易改造、功能更多,支持直接改换、使用tokenizer(原话是a direct access to a tokenizer,我没搞懂具体是啥意思?)和全部的推理功能。

以下两种方式都会展示:

1. Sequence Classification

Sequence Classification任务是将sequence在给定的类数中进行分类。如GLUE数据集。在GLUE数据集上进行微调可参考run_glue.py或run_xnli.py。

用pipeline进行情感分类的示例,使用在sst2(GLUE task)上微调过的模型,返回标签("POSITIVE""NEGATIVE")和得分:

from transformers import pipelineclassifier = pipeline("sentiment-analysis")result = classifier("I hate you")[0]
print(f"label: {result['label']}, with score: {round(result['score'], 4)}")result = classifier("I love you")[0]
print(f"label: {result['label']}, with score: {round(result['score'], 4)}")

输出:
label: NEGATIVE, with score: 0.9991
label: POSITIVE, with score: 0.9999

用AutoClass判断两句话是否同义(互为改写)的示例:

  1. 根据checkpoint名初始化tokenizer和模型,模型架构是BERT,并加载checkpoint中的权重
  2. 构建一个由两句话组成的sequence,含有正确的model-specific separators, token type ids and attention masks(由tokenizer自动生成)
  3. 将这个sequence传入模型,对它进行分类:是否同义
  4. 计算输出的softmax结果,获得在各类上的概率值
  5. 打印结果
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torchtokenizer = AutoTokenizer.from_pretrained("bert-base-cased-finetuned-mrpc")
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased-finetuned-mrpc")classes = ["not paraphrase", "is paraphrase"]sequence_0 = "The company HuggingFace is based in New York City"
sequence_1 = "Apples are especially bad for your health"
sequence_2 = "HuggingFace's headquarters are situated in Manhattan"# The tokenizer will automatically add any model specific separators (i.e. <CLS> and <SEP>) and tokens to
# the sequence, as well as compute the attention masks.
paraphrase = tokenizer(sequence_0, sequence_2, return_tensors="pt")
not_paraphrase = tokenizer(sequence_0, sequence_1, return_tensors="pt")paraphrase_classification_logits = model(**paraphrase).logits
not_paraphrase_classification_logits = model(**not_paraphrase).logitsparaphrase_results = torch.softmax(paraphrase_classification_logits, dim=1).tolist()[0]
not_paraphrase_results = torch.softmax(not_paraphrase_classification_logits, dim=1).tolist()[0]# Should be paraphrase
for i in range(len(classes)):print(f"{classes[i]}: {int(round(paraphrase_results[i] * 100))}%")# Should not be paraphrase
for i in range(len(classes)):print(f"{classes[i]}: {int(round(not_paraphrase_results[i] * 100))}%")

输出:not paraphrase: 10%
is paraphrase: 90%

not paraphrase: 94%
is paraphrase: 6%

2. Extractive Question Answering

Extractive Question Answering是从context(一段文本)中抽取句子,作为特定问题答句。如SQuAD1数据集。在SQuAD数据集上微调可参考run_qa.py。

用pipeline的示例,使用在SQuAD数据集上微调过的模型,返回从context中抽取的答案、confidence score、指示答案在context中位置的startend值:

from transformers import pipelinequestion_answerer = pipeline("question-answering")context = r"""
Extractive Question Answering is the task of extracting an answer from a text given a question. An example of a
question answering dataset is the SQuAD dataset, which is entirely based on that task. If you would like to fine-tune
a model on a SQuAD task, you may leverage the examples/pytorch/question-answering/run_squad.py script.
"""result = question_answerer(question="What is extractive question answering?", context=context)
print(f"Answer: '{result['answer']}', score: {round(result['score'], 4)}, start: {result['start']}, end: {result['end']}"
)result = question_answerer(question="What is a good example of a question answering dataset?", context=context)
print(f"Answer: '{result['answer']}', score: {round(result['score'], 4)}, start: {result['start']}, end: {result['end']}"
)

输出:
Answer: 'the task of extracting an answer from a text given a question', score: 0.6177, start: 34, end: 95
Answer: 'SQuAD dataset', score: 0.5152, start: 147, end: 160

用AutoClass的示例:

  1. 根据checkpoint名初始化tokenizer和模型,模型架构是BERT,并加载checkpoint中的权重
  2. 定义context和一些问题
  3. 迭代所有问题,构建context和当前问题的sequence(用正确的model-specific separators, token type ids and attention masks)
  4. 将这个sequence传入模型,输出整个sequence上每个token的得分(该token是start index或end index的可能性得分)。
  5. 计算输出的softmax结果,获得在各token上的概率值
  6. 获取被识别为startend之间的值的token,将其转化为字符串
  7. 打印结果
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
import torchtokenizer = AutoTokenizer.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")
model = AutoModelForQuestionAnswering.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")text = r"""
												

huggingface.transformers任务简介相关推荐

  1. Py之transformers:transformers的简介、安装、使用方法、案例应用之详细攻略

    Py之transformers:transformers的简介.安装.使用方法.案例应用之详细攻略 目录 transformers的简介 1.为什么要使用transformers? 2.文档.任务总结 ...

  2. 用huggingface.transformers在文本分类任务(单任务和多任务场景下)上微调预训练模型

    诸神缄默不语-个人CSDN博文目录 transformers官方文档:https://huggingface.co/docs/transformers/index AutoModel文档:https: ...

  3. Huggingface Transformers库学习笔记(二):使用Transformers(上)(Using Transformers Part 1)

    前言 本部分是Transformer库的基础部分的上半部分,主要包括任务汇总.模型汇总和数据预处理三方面内容,由于许多模型我也不太了解,所以多为机器翻译得到,错误再所难免,内容仅供参考. Huggin ...

  4. 使用 HuggingFace Transformers创建自己的搜索引擎

    创建Auto-Sommelier 2019年8月,我投入了我的第一个自然语言处理(NLP)项目,并在我的网站上托管了自动侍酒师(Auto-Sommelier).使用TensorFlow 1和Unive ...

  5. HuggingFace Transformers框架使用教程

    本文记录使用PyTorch.HuggingFace/Transformers 框架工作流程,仅供参考. 介绍 官网地址为Hugging Face.目前各种Pretrained的Transformer模 ...

  6. huggingface.transformers速成笔记:Pipeline推理和AutoClass

    诸神缄默不语-个人CSDN博文目录 本文属于huggingface.transformers全部文档学习笔记博文的一部分. 全文链接:huggingface transformers包 文档学习笔记( ...

  7. 【修改huggingface transformers默认缓存文件夹】

    How to change huggingface transformers default cache directory 前言 关于windows上如何修改huggingface transfor ...

  8. huggingface.transformers术语表

    诸神缄默不语-个人CSDN博文目录 本文属于huggingface.transformers全部文档学习笔记博文的一部分. 全文链接:huggingface transformers包 文档学习笔记( ...

  9. 2023年的深度学习入门指南(5) - HuggingFace Transformers库

    2023年的深度学习入门指南(5) - HuggingFace Transformers库 这一节我们来学习下预训练模型的封装库,Hugging Face的Transformers库的使用.Huggi ...

最新文章

  1. opencv 最大内接矩形笔记
  2. BootstrapTable-加载数据
  3. DStream算子讲解(一)
  4. .某学校的学生公寓有14栋楼,用A~N这14个大写字母的其中一个代表楼号,每栋楼的层数为6层,用1~6六个数字表示。每层楼有40个房间,编号为01~40。具体表示一个宿舍房间时,用1个字母加3位数字表
  5. win10一直卡在自动修复_分享:win10自动修复过程中无法正确启动怎么办?
  6. 西部数码linux云服务器,linux云服务器选择哪个版本
  7. OEM信息自定义工具v2.0
  8. 循序渐进之Spring AOP(1) - 原理
  9. 智能电能计量管理系统
  10. java 病毒查杀_Java清除exe文件中的病毒
  11. autocad怎么用计算机,职称计算机AutoCAD实用技巧
  12. 关于无迹卡尔曼滤波(UKF)的权重
  13. 蠕虫和从传统计算机病毒的区别主要体现在,蠕虫和传统计算机病毒的区别 病毒蠕虫和特洛伊木马...
  14. 关于java.lang.IllegalArgumentException: DrawerLayout must be measured with MeasureSpec.EXACTLY异常处理
  15. 浅显易懂了解JavaScript回调函数
  16. matlab中的motion,matlab-ego-motion 基于 实现的自身运动估计仿真程序。通过对视频图 分析,快速 摄像机 的 263万源代码下载- www.pudn.com...
  17. 给大家推荐几个不错的网站
  18. keystore/keymaster代码导读系列-ongoing
  19. 学Python划重点 四 (图形界面wxPython 库的使用)
  20. bat文件判断path路径是否包含其他路径

热门文章

  1. html实现鼠标跟随,html5实现鼠标跟随
  2. 1.19(Cake Baking)
  3. 实现vue2.0响应式原理
  4. char和数值的类型转换
  5. arch(linux)挂接小鹤音形输入法
  6. Linux系统的基本介绍
  7. C程序设计(谭浩强第五版)总结
  8. 华为云区块链的跨云联通能力构建
  9. 智源AI日报(2022-08-30): 华为谢凌曦:关于视觉识别领域发展的个人观点
  10. linux命令中ps -ef是什么意思