gpt4 book ai didi

nlp - 如何使用 BERT/GPT-2 进行释义生成

转载 作者:行者123 更新时间:2023-12-05 01:08:05 25 4
gpt4 key购买 nike

我正在努力了解如何使用 BERT/GPT-2 进行释义生成。我不明白我该怎么做。您能否提供我能够制作释义生成模型的任何资源?“输入是一个句子,输出是句子的释义”

最佳答案

这是我训练释义者的秘诀:

  1. 不要使用 BERT(仅编码器)或 GPT(仅解码器),而是使用带有编码器和解码器的 seq2seq 模型,例如 T5、BART 或 Pegasus。我建议使用 the multilingual T5 model这是针对 101 种语言进行预训练的。如果你想为你自己的语言加载嵌入(而不是使用全部 101),你可以关注 this recipe .

  2. 为您的语言和领域查找释义语料库。对于英语,ParaNMT、PAWS 和 QQP 是很好的候选。一个名为 Tapaco 的语料库,从 Tatoeba 中提取,是一个涵盖 73 种语言的释义语料库,因此如果您找不到适合您的语言的释义语料库,这是一个很好的起点。

  3. 在这个语料库上微调你的模型。代码可以是这样的:

import torch
from transformers import T5ForConditionalGeneration, T5Tokenizer
# use here a backbone model of your choice, e.g. google/mt5-base
backbone_model = 'cointegrated/rut5-base-multitask'
model = T5ForConditionalGeneration.from_pretrained(backbone_model)
tokenizer = T5Tokenizer.from_pretrained(backbone_model)
model.cuda();
optimizer = torch.optim.Adam(params=[p for p in model.parameters() if p.requires_grad], lr=1e-5)

# todo: load the paraphrasing corpus and define the get_batch function

for i in range(100500):
xx, yy = get_batch(mult=mult)
x = tokenizer(xx, return_tensors='pt', padding=True).to(model.device)
y = tokenizer(yy, return_tensors='pt', padding=True).to(model.device)
# do not force the model to predict pad tokens
y.input_ids[y.input_ids==0] = -100
loss = model(
input_ids=x.input_ids,
attention_mask=x.attention_mask,
labels=y.input_ids,
decoder_attention_mask=y.attention_mask,
return_dict=True
).loss
loss.backward()
optimizer.step()
optimizer.zero_grad()

model.save_pretrained('my_paraphraser')
tokenizer.save_pretrained('my_paraphraser')

可以找到此代码的更完整版本 in this notebook .

训练结束后,模型可以通过以下方式使用:

from transformers import pipeline
pipe = pipeline(task='text2text-generation', model='my_paraphraser')
print(pipe('Here is your text'))
# [{'generated_text': 'Here is the paraphrase or your text.'}]

如果您希望您的释义更加多样化,您可以使用 arguments 控制生成过程喜欢

print(pipe(
'Here is your text',
encoder_no_repeat_ngram_size=3, # make output different from input
do_sample=True, # randomize
num_beams=5, # try more options
max_length=128, # longer texts
))

享受吧!

关于nlp - 如何使用 BERT/GPT-2 进行释义生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66518316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com