-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrainmodels.py
217 lines (182 loc) · 10.5 KB
/
trainmodels.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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import numpy as np
#Applies computational budget by constraining training data size to a fraction of
#the total number of samples
def applyTrainingSamplesBudget(training_features, training_labels, budget_fraction):
training_size = len(training_labels)
budgeted_size = int(budget_fraction*training_size)
budgeted_training_features = training_features[:budgeted_size]
budgeted_training_labels = training_labels[:budgeted_size]
return budgeted_training_features, budgeted_training_labels
#Applies computational budget by constraining number of features in the training data
#to a fraction of the total number of features
def applyTrainingFeaturesBudget(training_features, validation_features, budget_fraction):
features_size = len(training_features[0])
budgeted_features = int(budget_fraction*features_size)
truncate_features = lambda lst : lst[:budgeted_features]
budgeted_training_features = list(map(truncate_features, training_features))
budgeted_validation_features = list(map(truncate_features, validation_features))
return budgeted_training_features, budgeted_validation_features
# Returns a function 'evaluate' that accepts hyperparameters for the specified
# machine learning algorithm and evaluates a model trained with these hyperparameters
# on the validation dataset
def evaluationFunctionGenerator(data, algorithm = 'svm-rbf', task='classification', **outerkwargs):
train_X = data['training_features']
train_y = data['training_labels']
validation_X = data['validation_features']
validation_y = data['validation_labels']
if 'budget_type' in outerkwargs.keys():
if 'budget_fraction' not in outerkwargs.keys():
raise ValueError('A budget fraction has not been provided.')
budget_fraction = outerkwargs['budget_fraction']
if outerkwargs['budget_type'] == 'samples':
train_X, train_y = applyTrainingSamplesBudget(train_X, train_y, budget_fraction)
elif outerkwargs['budget_type'] == 'features':
train_X, validation_X = applyTrainingFeaturesBudget(train_X, validation_X, budget_fraction)
# Ridge regression (1 hyperparameter)
if algorithm == 'ridge-regression' and task=='regression':
def evaluate(alpha, metric, **kwargs):
from sklearn.linear_model import Ridge
clf = Ridge(alpha = alpha)
clf.fit(train_X, train_y)
validation_predictions = clf.predict(validation_X)
return metric(validation_y, validation_predictions, **kwargs)
return evaluate
# SVM using radial basis function kernel (2 hyperparameters)
elif algorithm == 'svm-rbf' and task=='classification':
def evaluate(C, gamma, metric, **kwargs):
from sklearn import svm
clf = svm.SVC(C = C, kernel = 'rbf', gamma = gamma)
clf.fit(train_X, train_y)
#----------determine evaluation mode---------------
evaluation_mode = None
if 'evaluation_mode' not in kwargs.keys():
evaluation_mode = 'prediction'
else:
evaluation_mode = kwargs['evaluation_mode']
#----------generate predictions based on evaluation mode---------------
#The default is to use class predictions
validation_predictions = clf.predict(validation_X)
#This uses the raw score used to make the prediction i.e. distance from hyperplane
if evaluation_mode == 'raw-score':
validation_predictions = clf.decision_function(validation_X)
#----------return final metric---------------------
return metric(validation_y, validation_predictions, **kwargs)
return evaluate
# SVM using polynomial kernel (4 hyperparameters)
elif algorithm == 'svm-polynomial' and task=='classification':
def evaluate(C, gamma, constant_term, degree, metric, **kwargs):
from sklearn import svm
clf = svm.SVC(C = C, kernel = 'poly', gamma = gamma, degree = degree, coef0 = constant_term)
clf.fit(train_X, train_y)
#----------determine evaluation mode---------------
evaluation_mode = None
if 'evaluation_mode' not in kwargs.keys():
evaluation_mode = 'prediction'
else:
evaluation_mode = kwargs['evaluation_mode']
#----------generate predictions based on evaluation mode---------------
#The default is to use class predictions
validation_predictions = clf.predict(validation_X)
#This uses the raw score used to make the prediction i.e. distance from hyperplane
if evaluation_mode == 'raw-score':
validation_predictions = clf.decision_function(validation_X)
#----------return final metric---------------------
return metric(validation_y, validation_predictions, **kwargs)
return evaluate
# K-nearest neighbour regression (3 hyperparameters)
elif algorithm == 'knn-regression' and task == 'regression':
def evaluate(N, weightingFunction, distanceFunction, metric, **kwargs):
from sklearn.neighbors import KNeighborsRegressor
clf = None
if distanceFunction == 'minkowski': # Stands for generalised Minkowski distance
p = None
if 'p' not in kwargs.keys():
p = 2 # Use Euclidean distance by default
else:
p = kwargs['p'] # Use provided value of p
clf = KNeighborsRegressor(n_neighbors=int(N), weights=weightingFunction, p=p)
else:
clf = KNeighborsRegressor(n_neighbors=int(N), weights=weightingFunction, metric=distanceFunction)
clf.fit(train_X, train_y)
validation_predictions = clf.predict(validation_X)
return metric(validation_y, validation_predictions, **kwargs)
return evaluate
# K-nearest neighbour classification (3 hyperparameters)
elif algorithm == 'knn-classification' and task=='classification':
def evaluate(N, weightingFunction, distanceFunction, metric, **kwargs):
from sklearn.neighbors import KNeighborsClassifier
clf = None
#----------determine distance metric to be used---------------
if distanceFunction == 'minkowski': # Stands for generalised Minkowski distance
p = None
if 'p' not in kwargs.keys():
p = 2 # Use Euclidean distance by default
else:
p = kwargs['p'] # Use provided value of p
clf = KNeighborsClassifier(n_neighbors=int(N), weights=weightingFunction, p=p)
else:
clf = KNeighborsClassifier(n_neighbors=int(N), weights=weightingFunction, metric=distanceFunction)
clf.fit(train_X, train_y)
#----------determine evaluation mode---------------
evaluation_mode = None
if 'evaluation_mode' not in kwargs.keys():
evaluation_mode = 'prediction'
else:
evaluation_mode = kwargs['evaluation_mode']
#----------generate predictions based on evaluation mode---------------
#The default is to use class predictions
validation_predictions = clf.predict(validation_X)
#This uses the probability that the sample is from class 1
if evaluation_mode == 'probability':
extract_at_index_1 = lambda a : a[1]
validation_predictions = list(map(extract_at_index_1, clf.predict_proba(validation_X)))
#----------return final metric---------------------
return metric(validation_y, validation_predictions, **kwargs)
return evaluate
# Random forest classification (5 hyperparameters)
elif algorithm == 'random-forest' and task=='classification':
def evaluate(no_trees, max_tree_depth, bootstrap, min_samples_split, no_features, metric, **kwargs):
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=int(no_trees), max_depth=int(max_tree_depth), bootstrap=bootstrap, min_samples_split=int(min_samples_split), max_features=int(no_features), random_state=0)
clf.fit(train_X, train_y)
#----------determine evaluation mode---------------
evaluation_mode = None
if 'evaluation_mode' not in kwargs.keys():
evaluation_mode = 'prediction'
else:
evaluation_mode = kwargs['evaluation_mode']
#----------generate predictions based on evaluation mode---------------
#The default is to use class predictions
validation_predictions = clf.predict(validation_X)
#This uses the probability that the sample is from class 1
if evaluation_mode == 'probability':
extract_at_index_1 = lambda a : a[1]
validation_predictions = list(map(extract_at_index_1, clf.predict_proba(validation_X)))
#----------return final metric---------------------
return metric(validation_y, validation_predictions, **kwargs)
return evaluate
else:
raise ValueError('The algorithm specified is not recognised.')
#Generates a validation function based on cross validation, using evaluationFunctionGenerator
def crossValidationFunctionGenerator(descriptionDict, algorithm = 'svm-rbf', task='classification', **outerkwargs):
evalFunctions = [];
trainval_X = np.array(descriptionDict['trainval_features'])
trainval_y = np.array(descriptionDict['trainval_labels'])
no_splits = descriptionDict['no_splits']
for training_indices, val_indices in descriptionDict['index_generator']:
training_X, training_y = trainval_X[training_indices], trainval_y[training_indices]
val_X, val_y = trainval_X[val_indices], trainval_y[val_indices]
data = {
'training_features': training_X,
'training_labels': training_y,
'validation_features': val_X,
'validation_labels': val_y
}
newfunc = evaluationFunctionGenerator(data, algorithm=algorithm, task=task, **outerkwargs)
evalFunctions.append(newfunc)
def evaluate(*args, **kwargs):
result = 0
for func in evalFunctions:
result += func(*args, **kwargs)
return result/no_splits
return evaluate