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

问题描述

我正在努力理解如何使用 BERT/GPT-2 生成释义。我无法理解我是如何做到的。您能否提供任何资源让我能够制作释义生成模型? “输入将是一个句子,输出将是句子的释义”

解决方法

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

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

  2. 找到适合您的语言和领域的释义语料库。对于英语,ParaNMT、PAWS 和 QQP 是不错的选择。从 Tatoeba 提取的名为 Tapaco 的语料库是一个涵盖 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,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
))

享受吧!

,

您可以使用 T5 释义来生成释义