Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. def predict(net, char, h=None, top_k=None):
  2. ''' Given a character, predict the next character.
  3. Returns the predicted character and the hidden state.
  4. '''
  5.  
  6. # tensor inputs
  7. x = np.array([[net.char2int[char]]])
  8. x = one_hot_encode(x, len(net.chars))
  9. inputs = torch.from_numpy(x)
  10.  
  11. if(train_on_gpu):
  12. inputs = inputs.cuda()
  13.  
  14. # detach hidden state from history
  15. h = tuple([each.data for each in h])
  16. # get the output of the model
  17. out, h = net(inputs, h)
  18.  
  19. # get the character probabilities
  20. p = F.softmax(out, dim=1).data
  21. if(train_on_gpu):
  22. p = p.cpu() # move to cpu
  23.  
  24. # get top characters
  25. if top_k is None:
  26. top_ch = np.arange(len(net.chars))
  27. else:
  28. p, top_ch = p.topk(top_k)
  29. top_ch = top_ch.numpy().squeeze()
  30.  
  31. # select the likely next character with some element of randomness
  32. p = p.numpy().squeeze()
  33. char = np.random.choice(top_ch, p=p/p.sum())
  34.  
  35. # return the encoded value of the predicted char and the hidden state
  36. return net.int2char[char], h
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement