分类目录:《大模型从入门到应用》总目录
使用 pipeline() 是利用预训练模型进行推理的最简单的方式。你能够将 pipeline() 开箱即用地用于跨不同模态的多种任务,它支持的自然语言处理的任务列表:
TextClassificationPipeline:文本分类DocumentQuestionAnsweringPipeline:文档问答FillMaskPipeline:填充掩码FeatureExtractionPipeline:文本特征提取MaskGenerationPipeline:掩码生成NerPipeline:命名实体识别QuestionAnsweringPipeline:问答SummarizationPipeline:摘要生成TableQuestionAnsweringPipeline:表格问答Text2TextGenerationPipeline:文本到文本的生成TextGenerationPipeline:文本生成TokenClassificationPipeline:标记分类TranslationPipeline:翻译
文本分类任务PipelineTextClassificationPipeline
我们可以把 pipeline() 用在一个情感分析示例上,pipeline() 会下载并缓存一个用于情感分析的默认的预训练模型和分词器。然后我们就可以在目标文本上使用 classifier 了:
css
from transformers import pipeline
classifier = pipeline("sentiment-analysis")
classifier("We are very happy to show you the 🤗 Transformers library.")
输出:
css
[{'label': 'POSITIVE', 'score': 0.9997795224189758}]
如果你有不止一个输入,可以把所有输入放入一个列表然后传给pipeline(),它将会返回一个字典列表:
css
results = classifier(["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."])
for result in results:
print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
输出:
css
label: POSITIVE, with score: 0.9998
label: NEGATIVE, with score: 0.5309
pipeline() 可以容纳 HuggingFace Hub 中的任何模型,这让 pipeline() 更容易适用于其他用例。比如,你想要一个能够处理法语文本的模型,就可以使用 Hub 上的标记来筛选出合适的模型。靠前的筛选结果会返回一个为情感分析微调的多语言的 BERT 模型,你可以将它用于法语文本并使用 AutoModelForSequenceClassification 和 AutoTokenizer 来加载预训练模型和它关联的分词器:
css
from transformers import pipeline
from transformers import AutoTokenizer, AutoModelForSequenceClassification
model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
在 pipeline() 中指定模型和分词器,现在你就可以在法语文本上使用 classifier 了:
css
classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
classifier("Nous sommes très heureux de vous présenter la bibliothèque 🤗 Transformers.")
输出:
css
[{'label': '5 stars', 'score': 0.7272651791572571}]
对专栏中的内容有任何疑问均可联系博主微信(微信号:NeumannAI)咨询,作者也会持续优化文章叙述使得更多读者快速上手变现赚钱!
对专栏中的内容有任何疑问均可联系博主微信(微信号:NeumannAI)咨询,作者也会持续优化文章叙述使得更多读者快速上手变现赚钱!
参考文献:
1\] HuggingFace官方网站:https://huggingface.co/ \[2\] \[澳\]路易斯·汤斯顿 \[瑞士\]莱安德罗·冯·韦拉 \[法\]托马斯·沃尔夫. Transformer自然语言处理实战:使用Hugging Face Transformers库构建NLP应用\[M\]. 机械工业出版社, 2024 \[3\] 李福林. HuggingFace自然语言处理详解------基于BERT中文模型的任务实战\[M\]. 清华大学出版社, 2023