Search code examples
nlplstmrecurrent-neural-network

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


i want to create a prediction function which complete a part of "sentence" the model used here is a character based RNN(LSTM). what are the steps we should fellow ? i tried this but i can't give as input the sentence

 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

Solution

  • Here are two tutorial on how to use machine learning libraries to generate text Tensorflow and PyTorch.