-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest.py
126 lines (109 loc) · 3.43 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import argparse
import torch
import pandas as pd
from gensim.models import KeyedVectors
from tqdm import tqdm
from dataset import HierarchicalDataset, FlatDataset
from models import Fan, Han
from config import (
BATCH_SIZE,
PADDING,
DEVICE,
TQDM,
WORD_HIDDEN_SIZE,
SENT_HIDDEN_SIZE,
Yelp,
Yahoo,
Amazon,
Synthetic,
)
def main():
parser = argparse.ArgumentParser(description="Test the model")
parser.add_argument(
"dataset",
choices=["yelp", "yahoo", "amazon", "synthetic"],
help="Choose the dataset",
)
parser.add_argument(
"model",
choices=["fan", "han"],
help="Choose the model to be tested (flat or hierarchical",
)
parser.add_argument(
"model_file", help="File where the trained models is stored",
)
args = parser.parse_args()
if args.dataset == "yelp":
dataset_config = Yelp
elif args.dataset == "yahoo":
dataset_config = Yahoo
elif args.dataset == "amazon":
dataset_config = Amazon
elif args.dataset == "synthetic":
dataset_config = Synthetic
else:
# should not end there
exit()
wv = KeyedVectors.load(dataset_config.EMBEDDING_FILE)
test_df = pd.read_csv(dataset_config.TEST_DATASET).fillna("")
test_documents = test_df.text
test_labels = test_df.label
if args.model == "fan":
test_dataset = FlatDataset(
test_documents,
test_labels,
wv.vocab,
dataset_config.WORDS_PER_DOC[100],
)
else:
test_dataset = HierarchicalDataset(
test_documents,
test_labels,
wv.vocab,
dataset_config.SENT_PER_DOC[100],
dataset_config.WORDS_PER_SENT[100],
)
test_data_loader = torch.utils.data.DataLoader(
test_dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=6
)
if args.model == "fan":
model = Fan(
embedding_matrix=wv.vectors,
word_hidden_size=WORD_HIDDEN_SIZE,
num_classes=len(test_labels.unique()),
batch_size=BATCH_SIZE,
).to(DEVICE)
else:
model = Han(
embedding_matrix=wv.vectors,
word_hidden_size=WORD_HIDDEN_SIZE,
sent_hidden_size=SENT_HIDDEN_SIZE,
num_classes=len(test_labels.unique()),
batch_size=BATCH_SIZE,
).to(DEVICE)
model.load_state_dict(torch.load(args.model_file, map_location=DEVICE))
criterion = torch.nn.NLLLoss().to(DEVICE)
loss, acc = test_func(model, test_data_loader, criterion)
print(f"Loss: {loss:.4f}, Accuracy: {acc * 100:.1f}%")
def test_func(model, data_loader, criterion):
"Return the loss and the accuracy of the model on the input dataset"
model.eval()
losses = []
accs = []
with torch.no_grad():
for labels, features in tqdm(
data_loader, total=len(data_loader), disable=(not TQDM)
):
labels = labels.to(DEVICE)
features = features.to(DEVICE)
batch_size = len(labels)
model.init_hidden_state(batch_size)
outputs = model(features)
loss = criterion(outputs, labels)
losses.append(loss.item())
accs.append(
(outputs.argmax(1) == labels).sum().item() / batch_size
)
return sum(losses) / len(losses), sum(accs) / len(accs)
if __name__ == "__main__":
main()