训练 QA 模型

训练 QA 模型

本教程系列将涵盖txtai的主要用例,这是一个 AI 驱动的语义搜索平台。该系列的每章都有相关代码,可也可以在colab 中使用。
colab 地址

txtai 提供了一个训练管道,可用于使用 Transformers Trainer 框架以编程方式训练新模型。

此示例训练一个小型 QA 模型,然后使用几个新示例(少量学习)对其进行进一步微调。

安装依赖

安装txtai和所有依赖项。

pip install txtai datasets pandas

训练到 SQuAD 2.0 模型

第一步是训练 SQuAD 2.0 模型。SQuAD 是一个问答数据集,它提出一个带有上下文的问题以及已识别的答案。也有可能没有答案。有关更多信息,请参阅SQuAD 数据集网站。

为了提高效率,我们将使用带有一部分 SQuAD 2.0 的小型 Bert 模型。

from datasets import load_dataset
from txtai.pipeline import HFTrainer

ds = load_dataset("squad_v2")

trainer = HFTrainer()
trainer("google/bert_uncased_L-2_H-128_A-2", ds["train"].select(range(3000)), task="question-answering", output_dir="bert-tiny-squadv2")
print("Training complete")

对新数据进行微调

接下来,我们将添加一些其他示例。微调 QA 模型将有助于构建特定类型的问题或提高特定用例的性能。

对于具有狭窄用例的较小模型,这有助于模型将要提出的问题类型归零。在这种情况下,我们希望在询问成分时准确地告诉模型我们正在寻找的信息类型。这将有助于提高对模型生成的答案的信心。

# Training data
data = [
    {"question": "What ingredient?", "context": "Pour 1 can whole tomatoes", "answers": "tomatoes"},
    {"question": "What ingredient?", "context": "Dice 1 yellow onion", "answers": "onion"},
    {"question": "What ingredient?", "context": "Cut 1 red pepper", "answers": "pepper"},
    {"question": "What ingredient?", "context": "Peel and dice 1 clove garlic", "answers": "garlic"},
    {"question": "What ingredient?", "context": "Put 1/2 lb beef", "answers": "beef"},
]

model, tokenizer = trainer("bert-tiny-squadv2", data, task="question-answering", num_train_epochs=10)

测试模型

现在我们准备测试结果!以下部分针对仅使用 SQuAD 2.0 和进一步微调的模型训练的原始模型提出了一个问题。

from transformers import pipeline

questions = pipeline("question-answering", model="bert-tiny-squadv2")
questions("What ingredient?", "Peel and dice 1 shallot")
{'answer': 'dice 1 shallot',
 'end': 23,
 'score': 0.05128436163067818,
 'start': 9}
from transformers import pipeline

questions = pipeline("question-answering", model=model.to("cpu"), tokenizer=tokenizer)
questions("What ingredient?", "Peel and dice 1 shallot")
{'answer': 'shallot', 'end': 23, 'score': 0.13187439739704132, 'start': 16}

看看结果如何更有信心并有更好的答案。这种方法允许使用具有较窄功能集的较小模型,并具有提高速度的优势。用你自己的数据试试吧!

参考

https://dev.to/neuml/tutorial-series-on-txtai-ibg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发呆的比目鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值