用PyTorch和预训练的Transformers 创建问答系统

1.安装库(可以在google colab上运行)

pip install transformers

 2.导入库

成功安装transformer之后,而可以将库导入到python脚本中

from transformers import pipeline

 3.构建管道

在后台创建一个预先训练的问题回答模型以及它的标记器。在如下情况下使用的是DistilBERT-base模型

4.定义要询问的上下文和问题

context = """ 

Machine learning (ML) is the study of computer algorithms that improve automatically through experience. It is seen as a part of artificial intelligence. Machine learning algorithms build a model based on sample data, known as "training data", in order to make predictions or decisions without being explicitly programmed to do so. Machine learning algorithms are used in a wide variety of applications, such as email filtering and computer vision, where it is difficult or unfeasible to develop conventional algorithms to perform the needed tasks. 

"""

 并询问如下问题:

question = "What are machine learning models based on?"

5.回答问题

测试定义好的模型来回答相应的问题。我们可以通过将上下文和问题作为参数传递到实例化的管道并打印出结果来简单地运行问题来得出相应的回答

 result = question_answering(question=question, context=context) 

print("Answer:", result['answer']) 

print("Score:", result['score'])

得到如下结果:

 

参考于:https://zhuanlan.zhihu.com/p/345589230

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值