-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsklearn_classifier.py
134 lines (121 loc) · 4.59 KB
/
sklearn_classifier.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
131
132
133
import argparse
import numpy as np
from sklearn.feature_extraction.text import (TfidfVectorizer, CountVectorizer,
HashingVectorizer)
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.metrics import accuracy_score, matthews_corrcoef, \
precision_recall_fscore_support
from spec.dataset.corpora import available_corpora
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="sklearn classifier")
parser.add_argument("--corpus",
type=str,
choices=list(available_corpora.keys()),
default='sst',
help="corpus type",
required=True)
parser.add_argument("--train-path",
type=str,
default=None,
help="path to the train corpus",
required=True)
parser.add_argument("--test-path",
type=str,
default=None,
help="path to the test corpus",
required=True)
parser.add_argument("--feature",
type=str,
default="bow",
choices=['bow', 'tfidf', 'hash'],
help="features format")
args = parser.parse_args()
seed = 42
np.random.seed(42)
print('Reading train data...')
corpus_cls = available_corpora[args.corpus]
fields_tuples = corpus_cls.create_fields_tuples()
fields_dict = dict(fields_tuples)
corpus = corpus_cls(fields_tuples, lazy=True)
examples = corpus.read(args.train_path)
x_train, y_train = [], []
for ex in examples:
y_train.extend(ex.target)
text = ' '.join(ex.words)
if args.corpus == 'snli':
text = text + ' ' + ' '.join(ex.words_hyp)
x_train.append(text)
corpus.close()
y_train = np.array(y_train)
print('Vectorizing train data...')
if args.feature == 'bow':
vectorizer = CountVectorizer(lowercase=False)
features_train = vectorizer.fit_transform(x_train)
elif args.feature == 'bow':
vectorizer = TfidfVectorizer(lowercase=False)
features_train = vectorizer.fit_transform(x_train)
else:
vectorizer = HashingVectorizer(lowercase=False, n_features=2000)
features_train = vectorizer.fit_transform(x_train)
print('Training...')
# classifier_linear = LogisticRegression(
# C=1000,
# max_iter=1000,
# solver='lbfgs',
# multi_class='multinomial',
# penalty='l2',
# random_state=seed,
# n_jobs=2
# )
classifier_linear = SGDClassifier(
max_iter=50,
alpha=0.00001, # 0.0001
eta0=0.001, # not used for learning_rate=`optimal`
learning_rate='constant',
loss='hinge',
penalty='l2',
shuffle=True,
random_state=seed,
n_jobs=8,
verbose=1
)
classifier_linear.fit(features_train, y_train)
print('Reading test data...')
corpus = corpus_cls(fields_tuples, lazy=True)
examples = corpus.read(args.test_path)
x_test, y_test = [], []
for ex in examples:
y_test.extend(ex.target)
text = ' '.join(ex.words)
if args.corpus == 'snli':
text = text + ' ' + ' '.join(ex.words_hyp)
x_test.append(text)
corpus.close()
y_test = np.array(y_test)
print('Vectorizing test data...')
features_test = vectorizer.transform(x_test)
print('Predicting...')
y_train_pred = classifier_linear.predict(features_train)
y_test_pred = classifier_linear.predict(features_test)
print('Train')
print('-----')
acc = accuracy_score(y_train, y_train_pred)
mcc = matthews_corrcoef(y_train, y_train_pred)
prec, rec, f1, _ = precision_recall_fscore_support(y_train, y_train_pred,
average='macro')
print('Acc: {:.4f}'.format(acc))
print('Prec: {:.4f}'.format(prec))
print('Rec: {:.4f}'.format(rec))
print('F1: {:.4f}'.format(f1))
print('MCC: {:.4f}'.format(mcc))
print('Test')
print('-----')
acc = accuracy_score(y_test, y_test_pred)
mcc = matthews_corrcoef(y_test, y_test_pred)
prec, rec, f1, _ = precision_recall_fscore_support(y_test, y_test_pred,
average='macro')
print('Acc: {:.4f}'.format(acc))
print('Prec: {:.4f}'.format(prec))
print('Rec: {:.4f}'.format(rec))
print('F1: {:.4f}'.format(f1))
print('MCC: {:.4f}'.format(mcc))