-
Notifications
You must be signed in to change notification settings - Fork 2
/
IMDbTextCategorizationDemo.py
109 lines (84 loc) · 4.17 KB
/
IMDbTextCategorizationDemo.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
import argparse
import logging
import numpy as np
import keras
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from keras.datasets import imdb
from sklearn.feature_extraction.text import CountVectorizer
from tmu.models.classification.vanilla_classifier import TMClassifier
from tmu.tools import BenchmarkTimer
_LOGGER = logging.getLogger(__name__)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--num_clauses", default=10000, type=int)
parser.add_argument("--T", default=8000, type=int)
parser.add_argument("--s", default=2.0, type=float)
parser.add_argument("--device", default="GPU", type=str)
parser.add_argument("--weighted_clauses", default=True, type=bool)
parser.add_argument("--epochs", default=40, type=int)
parser.add_argument("--clause_drop_p", default=0.75, type=float)
parser.add_argument("--min_n", default=1, type=int)
parser.add_argument("--max_n", default=2, type=int)
parser.add_argument("--analyzer", default="word", type=str)
parser.add_argument("--features", default=5000, type=int)
parser.add_argument("--imdb-num-words", default=5000, type=int)
parser.add_argument("--imdb-index-from", default=2, type=int)
parser.add_argument("--max_included_literals", default=32, type=int)
args = parser.parse_args()
_LOGGER.info("Preparing dataset")
train, test = keras.datasets.imdb.load_data(num_words=args.imdb_num_words, index_from=args.imdb_index_from)
train_x, train_y = train
test_x, test_y = test
word_to_id = keras.datasets.imdb.get_word_index()
word_to_id = {k: (v + args.imdb_index_from) for k, v in word_to_id.items()}
word_to_id["<PAD>"] = 0
word_to_id["<START>"] = 1
word_to_id["<UNK>"] = 2
_LOGGER.info("Preparing dataset.... Done!")
_LOGGER.info("Producing bit representation...")
id_to_word = {value: key for key, value in word_to_id.items()}
training_documents = []
for i in range(train_y.shape[0]):
terms = []
for word_id in train_x[i]:
terms.append(id_to_word[word_id])
training_documents.append(" ".join(terms))
testing_documents = []
for i in range(test_y.shape[0]):
terms = []
for word_id in test_x[i]:
terms.append(id_to_word[word_id])
testing_documents.append(" ".join(terms))
vectorizer_X = CountVectorizer(
ngram_range=(args.min_n, args.max_n),
analyzer=args.analyzer,
lowercase=True,
binary=True
)
X_train = vectorizer_X.fit_transform(training_documents)
Y_train = train_y.astype(np.uint32)
X_test = vectorizer_X.transform(testing_documents)
Y_test = test_y.astype(np.uint32)
_LOGGER.info("Producing bit representation... Done!")
_LOGGER.info("Selecting Features....")
SKB = SelectKBest(chi2, k=args.features)
SKB.fit(X_train, Y_train)
selected_features = SKB.get_support(indices=True)
X_train = SKB.transform(X_train).toarray()
X_test = SKB.transform(X_test).toarray()
_LOGGER.info("Selecting Features.... Done!")
tm = TMClassifier(args.num_clauses, args.T, args.s, platform=args.device, weighted_clauses=args.weighted_clauses,
clause_drop_p=args.clause_drop_p)
_LOGGER.info(f"Running {TMClassifier} for {args.epochs}")
for epoch in range(args.epochs):
benchmark1 = BenchmarkTimer(logger=_LOGGER, text="Training Time")
with benchmark1:
tm.fit(X_train, Y_train)
benchmark2 = BenchmarkTimer(logger=_LOGGER, text="Testing Time")
with benchmark2:
Y_test_predicted, Y_test_scores = tm.predict(X_test, return_class_sums=True)
result = 100 * (Y_test_predicted == Y_test).mean()
_LOGGER.info(f"Epoch: {epoch + 1}, Accuracy: {result:.2f}, Training Time: {benchmark1.elapsed():.2f}s, "
f"Testing Time: {benchmark2.elapsed():.2f}s")
np.savetxt("class_sums/IMDBAnalyzer_%d_%d_%d_%.2f_%d_%d_%d_%d_%s_%.2f_%d.txt" % (epoch+1, args.num_clauses, args.T, args.s, args.min_n, args.max_n, args.max_included_literals, args.weighted_clauses, args.analyzer, args.clause_drop_p, args.features), Y_test_scores, delimiter=',')