Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. def featureEvaluate(encoder, decoder, char2i, pairs, use_cuda):
  2.     correct = 0
  3.     total = 0
  4.     i2char = {i: c for c, i in char2i.items()}
  5.     i=0
  6.     print_at = random.sample(range(1, 1000), 5)
  7.  
  8.     for inp, out in pairs:
  9.         preds = featurePredict(encoder, decoder, inp, use_cuda)
  10.         # Squeeze off the batch_size = 1 dim                                                                                                          
  11.         targets = out
  12.         total+=1
  13.         print("Evaluating dev example %i" % i)
  14.         if i in print_at:
  15.             print(''.join([i2char[int(c)] for c in preds]))
  16.             print(''.join([i2char[int(c)] for c in targets]))
  17.  
  18.         i+=1
  19.         if targets.equal(preds):
  20.             correct += 1
  21.  
  22.     return "Accuracy: %.2f %% \n" % (correct / total * 100)
  23.  
  24. def featurePredict(encoder, decoder, inp, use_cuda):
  25.     enc_out, enc_hidden = encoder(inp)
  26.  
  27.     decoder_input = Variable(torch.LongTensor([EOS_index]))
  28.  
  29.     dec_hidden = decoder.init_hidden()
  30.  
  31.     eos = 1
  32.     preds = []
  33.     while (eos < 2):
  34.         dec_out, dec_hidden = decoder(decoder_input,\
  35.                         dec_hidden, enc_out, use_cuda)
  36.  
  37.         topv, topi = dec_out.data.topk(1)
  38.         # Get the index from the tensor as an integer                                                                                                
  39.         topi_int = topi[0][0][0]
  40.         if topi_int == EOS_index:
  41.             eos += 1
  42.  
  43.         preds.append(topi_int)
  44.         decoder_input = Variable(topi.view(1))
  45.  
  46.     return Variable(torch.LongTensor(preds))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement