MCPcopy Create free account
hub / github.com/pytorch/tutorials / evaluate

Function evaluate

intermediate_source/char_rnn_classification_tutorial.py:379–412  ·  view source on GitHub ↗
(rnn, testing_data, classes)

Source from the content-addressed store, hash-verified

377#
378
379def evaluate(rnn, testing_data, classes):
380 confusion = torch.zeros(len(classes), len(classes))
381
382 rnn.eval() #set to eval mode
383 with torch.no_grad(): # do not record the gradients during eval phase
384 for i in range(len(testing_data)):
385 (label_tensor, text_tensor, label, text) = testing_data[i]
386 output = rnn(text_tensor)
387 guess, guess_i = label_from_output(output, classes)
388 label_i = classes.index(label)
389 confusion[label_i][guess_i] += 1
390
391 # Normalize by dividing every row by its sum
392 for i in range(len(classes)):
393 denom = confusion[i].sum()
394 if denom > 0:
395 confusion[i] = confusion[i] / denom
396
397 # Set up plot
398 fig = plt.figure()
399 ax = fig.add_subplot(111)
400 cax = ax.matshow(confusion.cpu().numpy()) #numpy uses cpu here so we need to use a cpu version
401 fig.colorbar(cax)
402
403 # Set up axes
404 ax.set_xticks(np.arange(len(classes)), labels=classes, rotation=90)
405 ax.set_yticks(np.arange(len(classes)), labels=classes)
406
407 # Force label at every tick
408 ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
409 ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
410
411 # sphinx_gallery_thumbnail_number = 2
412 plt.show()
413
414
415

Calls 1

label_from_outputFunction · 0.85

Tested by

no test coverage detected