【问题标题】:How do I make a paraphrase generation using BERT/ GPT-2如何使用 BERT/GPT-2 进行释义生成
【发布时间】:2021-06-05 15:43:39
【问题描述】:

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

【问题讨论】:

    标签: nlp gpt-2


    【解决方案1】:

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

    1. 不要使用 BERT(仅编码器)或 GPT(仅解码器),而是使用带有编码器和解码器的 seq2seq 模型,例如 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, 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.'}]
    

    如果你想让你的释义更加多样化,你可以使用argumentslike来控制生成过程

    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
    ))
    

    享受吧!

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 这不是一个正确的答案。对此进行详细说明。它如何解决 OP 的问题。
      猜你喜欢
      • 2021-12-16
      • 2021-03-13
      • 1970-01-01
      • 2019-12-06
      • 2020-11-28
      • 2021-08-14
      • 2022-12-07
      • 2020-08-14
      • 2011-10-08
      相关资源
      最近更新 更多