【问题标题】:Using DistilBERT for generating sentences of text使用 DistilBERT 生成文本句子
【发布时间】:2020-09-11 08:59:24
【问题描述】:

美好的一天, 我使用了很棒的库 huggingface 转换器来使用 GPT2 生成文本,效果很好:

tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
input_ids = torch.tensor(tokenizer.encode("Once upon a time there was")).unsqueeze(0)
model = GPT2LMHeadModel.from_pretrained("gpt2", pad_token_id=tokenizer.eos_token_id)
greedy_output = model.generate(input_ids, max_length=50)
print("Output:\n" + 100 * '-')
print(tokenizer.decode(greedy_output[0], skip_special_tokens=True))

我的问题是,现在我想做同样的事情,但使用更小更简单的 DistimBERT 模型,它也是 104 种语言的多语言,所以我想用这个更轻的模型生成例如西班牙语和英语的文本

我试过了

tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-multilingual-cased')
model = DistilBertForMaskedLM.from_pretrained('distilbert-base-multilingual-cased')
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)  # Batch size 1
outputs = model(input_ids, masked_lm_labels=input_ids)
loss, prediction_scores = outputs[:2]

但我不确定这是否适合使用。一旦我得到输出,我将如何从中获得短语的延续?

经过更多的测试,我可以使用 distilgpt2 很好地生成生成,问题是我想使用轻量级多语言模型 DistilmBERT(distilbert-base-multilingual-cased)进行多语言,有什么提示吗?

import torch
from transformers import *
from transformers import TFGPT2LMHeadModel, GPT2Tokenizer

tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
input_ids = torch.tensor(tokenizer.encode("Once upon a time")).unsqueeze(0)
model = GPT2LMHeadModel.from_pretrained("distilgpt2", pad_token_id=tokenizer.eos_token_id)
greedy_output = model.generate(input_ids, max_length=50) #greedy search

sample_outputs = model.generate(
    input_ids,
    do_sample=True, 
    max_length=50, 
    top_k=50, 
    top_p=0.95, 
    temperature=1,
    num_return_sequences=3
)

print("Output:\n" + 100 * '-')
for i, sample_output in enumerate(sample_outputs):
  print("{}: {}".format(i, tokenizer.decode(sample_output, skip_special_tokens=True)))`

谢谢你的帮助:)

【问题讨论】:

  • 我指的是 Distilmbert,而不是 Distilbert:Huggingface:“2019 年 12 月 6 日 - 更新我们发布 DistilmBERT:92% 的 bert-base-multilingual-cases 在 XNLI 上。该模型支持列出的 104 种不同语言在这里。”

标签: python huggingface-transformers


【解决方案1】:

我只是复制LysandreJikhere的答案

很遗憾,DistilmBERT 不能用于生成。这是因为 原始 BERT 模型的预训练方式,使用 masked 语言建模(MLM)。因此,它同时关注左派和 正确的上下文(你所在的标记左右两边的标记 试图生成),而对于生成模型只能访问 左侧上下文。

GPT-2 使用因果语言建模 (CLM) 进行训练,这就是它的原因 可以生成这样的连贯序列。我们实现一代 仅适用于 CLM 模型的方法,因为 MLM 模型不会生成任何内容 连贯。

在文档中,您可以找到适合任务的模型。

https://transformer.huggingface.co/ 中的一个简单示例

【讨论】:

  • 非常感谢,我明白了。不幸的是,到目前为止我还没有找到西班牙语预训练的 gpt-2 模型,希望有人会在某个时候发布一个,再次感谢你;)
猜你喜欢
  • 2020-04-02
  • 2021-07-08
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 2021-11-27
相关资源
最近更新 更多