| 97 | |
| 98 | |
| 99 | def evaluate(config, model, data_iter, test=False): |
| 100 | model.eval() |
| 101 | loss_total = 0 |
| 102 | predict_all = np.array([], dtype=int) |
| 103 | labels_all = np.array([], dtype=int) |
| 104 | with torch.no_grad(): |
| 105 | for texts, labels in data_iter: |
| 106 | outputs = model(texts) |
| 107 | loss = F.cross_entropy(outputs, labels) |
| 108 | loss_total += loss |
| 109 | labels = labels.data.cpu().numpy() |
| 110 | predic = torch.max(outputs.data, 1)[1].cpu().numpy() |
| 111 | labels_all = np.append(labels_all, labels) |
| 112 | predict_all = np.append(predict_all, predic) |
| 113 | |
| 114 | acc = metrics.accuracy_score(labels_all, predict_all) |
| 115 | if test: |
| 116 | report = metrics.classification_report(labels_all, predict_all, target_names=config.class_list, digits=4) |
| 117 | confusion = metrics.confusion_matrix(labels_all, predict_all) |
| 118 | return acc, loss_total / len(data_iter), report, confusion |
| 119 | return acc, loss_total / len(data_iter) |