python - 使用 CNTK 通过在每个生成步骤进行采样来生成序列

标签 python reinforcement-learning decoder cntk sequence-to-sequence

在具有编码器和解码器的 seq2seq 模型中,在每个生成步骤,softmax 层都会输出整个词汇表的分布。在CNTK中,使用C.hardmax函数可以轻松实现贪婪解码器。看起来像这样。

def create_model_greedy(s2smodel):
    # model used in (greedy) decoding (history is decoder's own output)
    @C.Function
    @C.layers.Signature(InputSequence[C.layers.Tensor[input_vocab_dim]])
    def model_greedy(input): # (input*) --> (word_sequence*)
        # Decoding is an unfold() operation starting from sentence_start.
        # We must transform s2smodel (history*, input* -> word_logp*) into a generator (history* -> output*)
        # which holds 'input' in its closure.
        unfold = C.layers.UnfoldFrom(lambda history: s2smodel(history, input) >> **C.hardmax**,
                                     # stop once sentence_end_index was max-scoring output
                                     until_predicate=lambda w: w[...,sentence_end_index],
                                     length_increase=length_increase)
        return unfold(initial_state=sentence_start, dynamic_axes_like=input)
    return model_greedy

但是,在每一步我不想以最大概率输出 token 。相反,我想要一个随机解码器,它根据词汇的概率分布生成一个标记。

我怎样才能做到这一点?任何帮助表示赞赏。谢谢。

最佳答案

您可以在采用 Hardmax 之前向输出添加噪声。特别是,您可以使用 C.random.gumbelC.random.gumbel_likeexp(output) 的比例进行采样。这被称为 gumbel-max trickcntk.random模块也包含其他分布,但如果您有对数概率,您很可能希望在 Hardmax 之前添加gumbel 噪声。一些代码:

@C.Function
def randomized_hardmax(x):
    noisy_x = x + C.random.gumbel_like(x)
    return C.hardmax(noisy_x)

然后将您的 hardmax 替换为 randomized_hardmax

关于python - 使用 CNTK 通过在每个生成步骤进行采样来生成序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45671038/

相关文章:

python - 如何在 python 3 中模拟 python 2 str.lower()

python - 【强化学习】为什么我的reward变成0就结束了?我在健身房环境方面遇到了一些麻烦

reinforcement-learning - Q-Learning 收敛到最优策略

python - 使用 Python 将 PDF 转换为图像

python - 为 web2py 应用程序安装 Python 模块

recurrent-neural-network - 如何在 PyTorch 中使用 LSTM 进行强化学习?

video - FFMPEG:解释任何编解码器函数指针的参数

c - 调试 C 中的断言错误

xml - 在 Swift 4 中实现自定义解码器

python - Pandas groupby 并计算列的唯一值