【问题标题】:How to perform roll-out of an RNN In pytorch如何在 pytorch 中执行 RNN 的推出
【发布时间】:2018-10-28 08:48:00
【问题描述】:

我将一个 RNN(具体来说是一个 GRU)训练成一个语言模型,大致如下:

inputs = [<start>, tok1, tok2, tok3, . . .]

outputs = [tok1, tok2, tok3, . . .]

h0 = initial state of all-zeros

gru_outputs, hn = gru(inputs, h0)

cost = loss (gru_outputs, outputs)

基本上在训练期间有一个“指导”输入,我将 target 标记从最后一步输入到当前步骤(教师强制?)。

现在这个 RNN 训练良好,并且收敛。但我不知道如何真正使用它从头开始生成序列。由于 gru 期望一个明确的输入参数,我如何告诉它使用最后一步的输出而不给它输入?

基本上我想要

roll_out = gru(h0, step_number = 10)

无法完全弄清楚如何做到这一点。我是否需要在训练和使用过程中使用不同的 API 并手动推出?

此要点中的完整代码(如果有任何用处):https://gist.github.com/evanthebouncy/b5039dc72d3d9fea66dad3306e479e6b

谢谢!

--埃文

【问题讨论】:

  • 所以你正在训练一个语言模型,但是你不知道如何用训练好的模型创建一个文本序列?
  • 是的。有什么帮助吗? 1个字符

标签: pytorch rnn


【解决方案1】:

因此,如果您想通过生成随机文本来测试您的语言模型 - 只需选择一个随机标记作为第一个单词。输入这个随机词后,模型将生成一个输出,然后您刚刚生成的这个词将成为您输入模型的下一个输入,依此类推。

以下是一些示例代码:

# Test the model
with torch.no_grad():
    with open('sample.txt', 'w') as f:
        # Set intial hidden ane cell states
        state = (torch.zeros(num_layers, 1, hidden_size).to(device),
                 torch.zeros(num_layers, 1, hidden_size).to(device))

        # Select one word id randomly
        prob = torch.ones(vocab_size)
        input = torch.multinomial(prob, num_samples=1).unsqueeze(1).to(device)

        for i in range(num_samples):
            # Forward propagate RNN 
            output, state = model(input, state)

            # Sample a word id
            prob = output.exp()
            word_id = torch.multinomial(prob, num_samples=1).item()

            # Fill input with sampled word id for the next time step
            input.fill_(word_id)

            # File write
            word = corpus.dictionary.idx2word[word_id]
            word = '\n' if word == '<eos>' else word + ' '
            f.write(word)

            if (i+1) % 100 == 0:
                print('Sampled [{}/{}] words and save to {}'.format(i+1, num_samples, 'sample.txt'))

该模型的完整代码也可以在here找到。

您可能需要稍微修改代码以使其适用于您的模型。

【讨论】:

  • 你正在使用的这个函数,“模型”,它需要什么?它需要一个输入和一个隐藏状态,对吧?这正是我的问题。我正在训练的代码“gru”接受输入的序列,而不是单个标记。我不知道如何让训练模型执行单步计算。我的解决方法是继续附加到输入(注意,inputs,带有 s)数组并每次重新计算输出,这是非常低效的。我在问如何处理这个问题。
  • 你可以输入任何你想要的序列长度,模型对此没有限制。创建模型后修复的只是输入的暗淡。
猜你喜欢
  • 2019-03-28
  • 2020-10-19
  • 2018-10-13
  • 1970-01-01
  • 2017-11-19
  • 2019-07-21
  • 2020-09-30
  • 1970-01-01
  • 2018-11-23
相关资源
最近更新 更多