-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
130 lines (97 loc) · 3.52 KB
/
run.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
127
128
129
130
from time import time
from nltk import NaiveBayesClassifier
from nltk.classify import accuracy
from nltk import ConfusionMatrix
from sklearn.cross_validation import StratifiedKFold
import numpy as np
import os.path
from os import makedirs
import pickle
import preprocess
def print_result(_result):
"""
Modular printing for easier debugging. Add whatever output you want to see
"""
#_result['classifier'].show_most_informative_features(10)
#print("Confusion Matrix:")
#print(_result['confusion'].pretty_format())
print("\tAccuracy = {}".format(_result['accuracy']))
print("\tPrecision = {}".format(_result['precision']))
print("\tRecall = {}".format(_result['recall']))
print("\tF-score = {}".format(_result['F-score']))
print("\tType 1 err = {}".format(_result['Type 1 err']))
print("\tType 2 err = {}".format(_result['Type 2 err']))
print("\n##########\n")
def train_classifiers(_labelled_features, _folds):
"""
Train a set of ten classifiers and save their results in dicts.
:param _labelled_features:
:param _folds:
:return:
"""
_results = []
i = 0
for train_inds, test_inds in _folds:
i += 1
result = {}
train_set = _labelled_features[train_inds]
test_set = _labelled_features[test_inds]
classifier = NaiveBayesClassifier.train(train_set)
result['accuracy'] = accuracy(classifier, test_set)
result['train_inds'] = train_inds
result['test_inds'] = test_inds
result['classifier'] = classifier
pred = []
test_labels = list(test_set.transpose()[1])
for t in test_set:
pred.append(classifier.classify(t[0]))
confusion = ConfusionMatrix(test_labels, pred)
tp = confusion['p', 'p']
tn = confusion['n', 'n']
fp = confusion['n', 'p']
fn = confusion['p', 'n']
precision = tp / (tp + fp)
recall = tp / (tp + fn)
result['test_labels'] = test_labels
result['pred_labels'] = pred
result['confusion'] = confusion
result['precision'] = precision
result['recall'] = recall
result['F-score'] = (2 * precision * recall) / (precision + recall)
result['Type 1 err'] = fp / (tp + fp)
result['Type 2 err'] = fn / (tn + fn)
_results.append(result)
return _results
def pickle_results(_results):
"""
Serialise and save a trained classifier result using pickle.
:param _results:
:return:
"""
timestamp = int(time() * 1000)
results_fi = 'naive_bayes_results-{}.pickle'.format(timestamp)
results_file = os.path.join('results', results_fi)
results_dir = os.path.dirname(results_file)
if not os.path.exists(results_dir):
makedirs(results_dir)
print("Saving results to {}".format(results_file))
with open(results_file, 'wb') as fi:
pickle.dump(_results, fi)
if __name__ == '__main__':
# TODO: smoothing? Don't think this is done automatically by NLTK
print("Loading data...")
num_words = None
features, labels = preprocess.load_data_and_labels(num_words)
folds = StratifiedKFold(labels, 10)
labelled_features = zip(features, labels)
labelled_features = np.array(list(labelled_features))
results = []
i = 0
print("Training models...")
results = train_classifiers(labelled_features, folds)
for i, r in enumerate(results):
print("Fold {}".format(i))
print_result(r)
print("Saving results...")
pickle_results(results)
print("Done!")