-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
93 lines (66 loc) · 2.25 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
import torch
import torch.nn as nn
import re
from torchtext.vocab import GloVe
from torch.utils.data import DataLoader
from torch.nn.utils.rnn import pad_sequence
from model import CNN, reset_weights
from datasets import create_datasets
from utils import evaluate
def text_pipeline(text):
"""Processes the input text and returns a tensor representation."""
tokens = re.findall(r"\b\w+\b", text)
tensor = vocab(tokens)
return tensor
# Load the vocabulary
vocab = torch.load('outputs/vocab.pth')
# Load pretrained embeddings
global_vectors = GloVe(name='twitter.27B', dim=200)
# Get the pre-trained embeddings for the words in the vocabulary
words = vocab.get_itos()
embeddings = global_vectors.get_vecs_by_tokens(words)
def collate_batch(data):
inputs, labels = [], []
for (_text, _label) in data:
inputs.append(torch.tensor(text_pipeline(_text), dtype=torch.int64))
labels.append(int(_label))
# Pad sequential data to a max length of a batch
inputs = pad_sequence(inputs, batch_first=True)
labels = torch.tensor(labels)
return {
'text': inputs,
'labels': labels
}
# Set the computation device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Define model hyperparameters
EMBEDDING_DIM = 200
N_FILTERS = 200
FILTER_SIZES = [3, 4, 5]
OUTPUT_DIM = 3
DROPOUT = 0.5
model = CNN(
embeddings,
True,
None,
EMBEDDING_DIM,
N_FILTERS,
FILTER_SIZES,
OUTPUT_DIM,
DROPOUT).to(device)
reset_weights(model)
# Load the best model
checkpoint = torch.load('outputs/model.pth')
model.load_state_dict(checkpoint['model_state_dict'])
# Get the test dataset
train_data, test_data = create_datasets('inputs/train.json')
BATCH_SIZE = 32
# Create a data loader for the test set
test_dataloader = DataLoader(test_data,
batch_size=BATCH_SIZE,
collate_fn=collate_batch)
# Define the loss function
criterion = nn.CrossEntropyLoss().to(device)
# Evaluate the model on the test set
test_loss, test_acc = evaluate(model, test_dataloader, criterion, device)
print(f'Test Loss: {test_loss:.3f} | Test Acc: {test_acc*100:.2f}%')