如何基于基于字符的 RNN 模型预测字符?

how to predict a character based on character based RNN model?

我想创建一个预测函数来完成“句子”的一部分 这里使用的模型是基于字符的 RNN(LSTM)。我们应该遵循哪些步骤? 我试过了,但我不能输入句子

 def generate(self) -> Tuple[List[Token], torch.tensor]:

    start_symbol_idx = self.vocab.get_token_index(START_SYMBOL, 'tokens')
   # print(start_symbol_idx)
    end_symbol_idx = self.vocab.get_token_index(END_SYMBOL, 'tokens')
    padding_symbol_idx = self.vocab.get_token_index(DEFAULT_PADDING_TOKEN, 'tokens')

    log_likelihood = 0.
    words = []
    state = (torch.zeros(1, 1, self.hidden_size), torch.zeros(1, 1, self.hidden_size))

    word_idx = start_symbol_idx

    for i in range(self.max_len):
        tokens = torch.tensor([[word_idx]])

        embeddings = self.embedder({'tokens': tokens})
        output, state = self.rnn._module(embeddings, state)
        output = self.hidden2out(output)

        log_prob = torch.log_softmax(output[0, 0], dim=0)

        dist = torch.exp(log_prob)

        word_idx = start_symbol_idx

        while word_idx in {start_symbol_idx, padding_symbol_idx}:
            word_idx = torch.multinomial(
                dist, num_samples=1, replacement=False).item()

        log_likelihood += log_prob[word_idx]

        if word_idx == end_symbol_idx:
            break

        token = Token(text=self.vocab.get_token_from_index(word_idx, 'tokens'))
        words.append(token)

    return words, log_likelihood,start_symbol_idx

这里有两个关于如何使用机器学习库生成文本的教程Tensorflow and PyTorch

这段代码片段是allennlp“语言模型”教程的一部分,这里定义了generate函数来计算token的概率,根据模型输出的最大似然找到最好的token和token序列,即完整代码在下面的 colab notebook 中,您可以参考它:https://colab.research.google.com/github/mhagiwara/realworldnlp/blob/master/examples/generation/lm.ipynb#scrollTo=8AU8pwOWgKxE 在训练使用此功能的语言模型后,您可以说:

for _ in range(50):
  tokens, _ = model.generate()
  print(''.join(token.text for token in tokens))