赞
踩
近年来,由于在数百万个网页数据上训练的大型基于 Transformer 的语言模型的兴起,开放式语言生成引起了越来越多的关注,其中包括OpenAI著名的GPT2模型。在条件开放式语言生成方面,取得了令人瞩目的成果。除了改进的 Transformer 架构和大规模无监督训练数据外,更好的解码方法也起到了重要作用。
本文简要介绍了不同的解码策略,并展示了如何使用 huggingface 的 transformers 库来轻松实现它们!
本文介绍的所有功能都能用于自回归语言生成。简而言之,自回归语言生成是基于这样的假设,即一个词序列的概率分布可以分解为下一个词条件概率分布的乘积:
其中 W0 是初始上下文词序列;单词序列的长度 T 通常是生成时即时 (on-the-fly) 确定的,即当某个时刻 t 出现了 EOS token 则可以停止单词序列生成。
!pip install -q git+https://github.com/huggingface/transformers.git
!pip install -q tensorflow==2.1
import tensorflow as tf
from transformers import TFGPT2LMHeadModel, GPT2Tokenizer
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
# add the EOS token as PAD token to avoid warnings
model = TFGPT2LMHeadModel.from_pretrained("gpt2", pad_token_id=tokenizer.eos_token_id)
Greedy search 每次都选择概率最大的词作为单词序列中的下一个词
从 “The” 这个词开始,每一步都选择概率最大的单词,分别选择了 “nice” 和 “woman”,最后这样选择的整体概率为
0.5
×
0.4
=
0.2
0.5 \times 0.4=0.2
0.5×0.4=0.2
接下来,我们将使用GPT2在上下文(“I”, “enjoy”, “walking”, “with”, “my”, “cute”, “dog”)上生成单词序列(“I”,“enjoy”,“walking”,“with”,“my”,“cute”,“dog”)。让我们看看在transformers中如何使用贪婪搜索:
# encode context the generation is conditioned on
input_ids = tokenizer.encode('I enjoy walking with my cute dog', return_tensors='tf')
# generate text until the output length (which includes the context length) reaches 50
greedy_output = model.generate(input_ids, max_length=50)
print("Output:\n" + 100 * '-')
print(tokenizer.decode(greedy_output[0], skip_special_tokens=True))
# Output:
# ----------------------------------------------------------------------------------------------------
# I enjoy walking with my cute dog, but I'm not sure if I'll ever be able to walk with my dog. I'm not sure if I'll ever be able to walk with my dog.
# I'm not sure if I'll
太好了!我们使用GPT2生成了我们的第一个短文本声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。