-
Notifications
You must be signed in to change notification settings - Fork 0
/
combine_uea.py
151 lines (137 loc) · 5.53 KB
/
combine_uea.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import os
import json
import numpy
import torch
import sklearn
import argparse
import uea
import scikit_wrappers
def load_classifier(save_path, dataset, cuda, gpu):
"""
Loads and returns classifier from the given parameters.
@param save_path Path where the model is located.
@param dataset Name of the dataset.
@param cuda If True, enables computations on the GPU.
@param gpu GPU to use if CUDA is enabled.
"""
classifier = scikit_wrappers.CausalCNNEncoderClassifier()
hf = open(
os.path.join(
save_path,
dataset + '_hyperparameters.json'
), 'r'
)
hp_dict = json.load(hf)
hf.close()
hp_dict['cuda'] = cuda
hp_dict['gpu'] = gpu
classifier.set_params(**hp_dict)
classifier.load(os.path.join(save_path, dataset))
return classifier
def parse_arguments():
parser = argparse.ArgumentParser(
description='Classification tests for UEA repository datasets, ' +
'using the features of several precomputed encoders, ' +
'possibly with different hyperparameters, and combining ' +
'their computed representations to train an SVM on top ' +
'of them.'
)
parser.add_argument('--dataset', type=str, metavar='D', required=True,
help='dataset name')
parser.add_argument('--path', type=str, metavar='PATH', required=True,
help='path where the dataset is located')
parser.add_argument('--model_path', type=str, metavar='PATH',
required=True,
help='path where the folders containing models for ' +
'different hyperparameters are located')
parser.add_argument('--folders', type=str, metavar='FOLDERS',
required=True, nargs='+',
help='list of folders, each one containing a model ' +
'for the chosen dataset')
parser.add_argument('--save_path', type=str, metavar='PATH', required=True,
help='path where the classifier is/should be saved')
parser.add_argument('--load', action='store_true', default=False,
help='activate to load the classifier instead of ' +
'training it')
parser.add_argument('--cuda', action='store_true',
help='activate to use CUDA')
parser.add_argument('--gpu', type=int, default=0, metavar='GPU',
help='index of GPU used for computations (default: 0)')
return parser.parse_args()
if __name__ == '__main__':
args = parse_arguments()
if args.cuda and not torch.cuda.is_available():
print("CUDA is not available, proceeding without it...")
args.cuda = False
# Train, test datasets
train, train_labels, test, test_labels = uea.load_UEA_dataset(
args.path, args.dataset
)
# List of classifiers
classifiers = [
load_classifier(
os.path.join(args.model_path, folder), args.dataset, args.cuda,
args.gpu
) for folder in args.folders
]
train_representations = numpy.concatenate([
c.encode(train) for c in classifiers
], axis=1)
test_representations = numpy.concatenate([
c.encode(test) for c in classifiers
], axis=1)
classifier = sklearn.svm.SVC(C=numpy.inf, gamma='scale')
if not args.load:
nb_classes = numpy.shape(
numpy.unique(train_labels, return_counts=True)[1]
)[0]
train_size = numpy.shape(train_representations)[0]
if train_size // nb_classes < 5 or train_size < 50:
classifier.fit(train_representations, train_labels)
else:
grid_search = sklearn.model_selection.GridSearchCV(
classifier, {
'C': [
0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 10000,
numpy.inf
],
'kernel': ['rbf'],
'degree': [3],
'gamma': ['scale'],
'coef0': [0],
'shrinking': [True],
'probability': [False],
'tol': [0.001],
'cache_size': [200],
'class_weight': [None],
'verbose': [False],
'max_iter': [10000000],
'decision_function_shape': ['ovr'],
'random_state': [None]
},
cv=5, iid=False, n_jobs=5
)
if train_size <= 10000:
grid_search.fit(train_representations, train_labels)
else:
# If the training set is too large, subsample 10000 train
# examples
split = sklearn.model_selection.train_test_split(
train_representations, train_labels,
train_size=10000, random_state=0, stratify=train_labels
)
grid_search.fit(split[0], split[2])
classifier = grid_search.best_estimator_
sklearn.externals.joblib.dump(
classifier, os.path.join(
args.save_path, args.dataset + '_CausalCNN_classifier.pkl'
)
)
else:
classifier = sklearn.externals.joblib.load(os.path.join(
args.save_path, args.dataset + '_CausalCNN_classifier.pkl'
))
# Testing
print("Test accuracy: " + str(
classifier.score(test_representations, test_labels)
))