comparison search_model_validation.py @ 0:8e93241d5d28 draft default tip

planemo upload for repository https://github.com/bgruening/galaxytools/tree/master/tools/sklearn commit c0a3a186966888e5787335a7628bf0a4382637e7
author bgruening
date Tue, 14 May 2019 18:04:46 -0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:8e93241d5d28
1 import argparse
2 import collections
3 import imblearn
4 import json
5 import numpy as np
6 import pandas
7 import pickle
8 import skrebate
9 import sklearn
10 import sys
11 import xgboost
12 import warnings
13 import iraps_classifier
14 import model_validations
15 import preprocessors
16 import feature_selectors
17 from imblearn import under_sampling, over_sampling, combine
18 from scipy.io import mmread
19 from mlxtend import classifier, regressor
20 from sklearn import (cluster, compose, decomposition, ensemble,
21 feature_extraction, feature_selection,
22 gaussian_process, kernel_approximation, metrics,
23 model_selection, naive_bayes, neighbors,
24 pipeline, preprocessing, svm, linear_model,
25 tree, discriminant_analysis)
26 from sklearn.exceptions import FitFailedWarning
27 from sklearn.externals import joblib
28 from sklearn.model_selection._validation import _score
29
30 from utils import (SafeEval, get_cv, get_scoring, get_X_y,
31 load_model, read_columns)
32 from model_validations import train_test_split
33
34
35 N_JOBS = int(__import__('os').environ.get('GALAXY_SLOTS', 1))
36 CACHE_DIR = './cached'
37 NON_SEARCHABLE = ('n_jobs', 'pre_dispatch', 'memory', 'steps',
38 'nthread', 'verbose')
39
40
41 def _eval_search_params(params_builder):
42 search_params = {}
43
44 for p in params_builder['param_set']:
45 search_list = p['sp_list'].strip()
46 if search_list == '':
47 continue
48
49 param_name = p['sp_name']
50 if param_name.lower().endswith(NON_SEARCHABLE):
51 print("Warning: `%s` is not eligible for search and was "
52 "omitted!" % param_name)
53 continue
54
55 if not search_list.startswith(':'):
56 safe_eval = SafeEval(load_scipy=True, load_numpy=True)
57 ev = safe_eval(search_list)
58 search_params[param_name] = ev
59 else:
60 # Have `:` before search list, asks for estimator evaluatio
61 safe_eval_es = SafeEval(load_estimators=True)
62 search_list = search_list[1:].strip()
63 # TODO maybe add regular express check
64 ev = safe_eval_es(search_list)
65 preprocessors = (
66 preprocessing.StandardScaler(), preprocessing.Binarizer(),
67 preprocessing.Imputer(), preprocessing.MaxAbsScaler(),
68 preprocessing.Normalizer(), preprocessing.MinMaxScaler(),
69 preprocessing.PolynomialFeatures(),
70 preprocessing.RobustScaler(), feature_selection.SelectKBest(),
71 feature_selection.GenericUnivariateSelect(),
72 feature_selection.SelectPercentile(),
73 feature_selection.SelectFpr(), feature_selection.SelectFdr(),
74 feature_selection.SelectFwe(),
75 feature_selection.VarianceThreshold(),
76 decomposition.FactorAnalysis(random_state=0),
77 decomposition.FastICA(random_state=0),
78 decomposition.IncrementalPCA(),
79 decomposition.KernelPCA(random_state=0, n_jobs=N_JOBS),
80 decomposition.LatentDirichletAllocation(
81 random_state=0, n_jobs=N_JOBS),
82 decomposition.MiniBatchDictionaryLearning(
83 random_state=0, n_jobs=N_JOBS),
84 decomposition.MiniBatchSparsePCA(
85 random_state=0, n_jobs=N_JOBS),
86 decomposition.NMF(random_state=0),
87 decomposition.PCA(random_state=0),
88 decomposition.SparsePCA(random_state=0, n_jobs=N_JOBS),
89 decomposition.TruncatedSVD(random_state=0),
90 kernel_approximation.Nystroem(random_state=0),
91 kernel_approximation.RBFSampler(random_state=0),
92 kernel_approximation.AdditiveChi2Sampler(),
93 kernel_approximation.SkewedChi2Sampler(random_state=0),
94 cluster.FeatureAgglomeration(),
95 skrebate.ReliefF(n_jobs=N_JOBS),
96 skrebate.SURF(n_jobs=N_JOBS),
97 skrebate.SURFstar(n_jobs=N_JOBS),
98 skrebate.MultiSURF(n_jobs=N_JOBS),
99 skrebate.MultiSURFstar(n_jobs=N_JOBS),
100 imblearn.under_sampling.ClusterCentroids(
101 random_state=0, n_jobs=N_JOBS),
102 imblearn.under_sampling.CondensedNearestNeighbour(
103 random_state=0, n_jobs=N_JOBS),
104 imblearn.under_sampling.EditedNearestNeighbours(
105 random_state=0, n_jobs=N_JOBS),
106 imblearn.under_sampling.RepeatedEditedNearestNeighbours(
107 random_state=0, n_jobs=N_JOBS),
108 imblearn.under_sampling.AllKNN(random_state=0, n_jobs=N_JOBS),
109 imblearn.under_sampling.InstanceHardnessThreshold(
110 random_state=0, n_jobs=N_JOBS),
111 imblearn.under_sampling.NearMiss(
112 random_state=0, n_jobs=N_JOBS),
113 imblearn.under_sampling.NeighbourhoodCleaningRule(
114 random_state=0, n_jobs=N_JOBS),
115 imblearn.under_sampling.OneSidedSelection(
116 random_state=0, n_jobs=N_JOBS),
117 imblearn.under_sampling.RandomUnderSampler(
118 random_state=0),
119 imblearn.under_sampling.TomekLinks(
120 random_state=0, n_jobs=N_JOBS),
121 imblearn.over_sampling.ADASYN(random_state=0, n_jobs=N_JOBS),
122 imblearn.over_sampling.RandomOverSampler(random_state=0),
123 imblearn.over_sampling.SMOTE(random_state=0, n_jobs=N_JOBS),
124 imblearn.over_sampling.SVMSMOTE(random_state=0, n_jobs=N_JOBS),
125 imblearn.over_sampling.BorderlineSMOTE(
126 random_state=0, n_jobs=N_JOBS),
127 imblearn.over_sampling.SMOTENC(
128 categorical_features=[], random_state=0, n_jobs=N_JOBS),
129 imblearn.combine.SMOTEENN(random_state=0),
130 imblearn.combine.SMOTETomek(random_state=0))
131 newlist = []
132 for obj in ev:
133 if obj is None:
134 newlist.append(None)
135 elif obj == 'all_0':
136 newlist.extend(preprocessors[0:36])
137 elif obj == 'sk_prep_all': # no KernalCenter()
138 newlist.extend(preprocessors[0:8])
139 elif obj == 'fs_all':
140 newlist.extend(preprocessors[8:15])
141 elif obj == 'decomp_all':
142 newlist.extend(preprocessors[15:26])
143 elif obj == 'k_appr_all':
144 newlist.extend(preprocessors[26:30])
145 elif obj == 'reb_all':
146 newlist.extend(preprocessors[31:36])
147 elif obj == 'imb_all':
148 newlist.extend(preprocessors[36:55])
149 elif type(obj) is int and -1 < obj < len(preprocessors):
150 newlist.append(preprocessors[obj])
151 elif hasattr(obj, 'get_params'): # user uploaded object
152 if 'n_jobs' in obj.get_params():
153 newlist.append(obj.set_params(n_jobs=N_JOBS))
154 else:
155 newlist.append(obj)
156 else:
157 sys.exit("Unsupported estimator type: %r" % (obj))
158
159 search_params[param_name] = newlist
160
161 return search_params
162
163
164 def main(inputs, infile_estimator, infile1, infile2,
165 outfile_result, outfile_object=None, groups=None):
166 """
167 Parameter
168 ---------
169 inputs : str
170 File path to galaxy tool parameter
171
172 infile_estimator : str
173 File path to estimator
174
175 infile1 : str
176 File path to dataset containing features
177
178 infile2 : str
179 File path to dataset containing target values
180
181 outfile_result : str
182 File path to save the results, either cv_results or test result
183
184 outfile_object : str, optional
185 File path to save searchCV object
186
187 groups : str
188 File path to dataset containing groups labels
189 """
190
191 warnings.simplefilter('ignore')
192
193 with open(inputs, 'r') as param_handler:
194 params = json.load(param_handler)
195 if groups:
196 (params['search_schemes']['options']['cv_selector']
197 ['groups_selector']['infile_g']) = groups
198
199 params_builder = params['search_schemes']['search_params_builder']
200
201 input_type = params['input_options']['selected_input']
202 if input_type == 'tabular':
203 header = 'infer' if params['input_options']['header1'] else None
204 column_option = (params['input_options']['column_selector_options_1']
205 ['selected_column_selector_option'])
206 if column_option in ['by_index_number', 'all_but_by_index_number',
207 'by_header_name', 'all_but_by_header_name']:
208 c = params['input_options']['column_selector_options_1']['col1']
209 else:
210 c = None
211 X = read_columns(
212 infile1,
213 c=c,
214 c_option=column_option,
215 sep='\t',
216 header=header,
217 parse_dates=True).astype(float)
218 else:
219 X = mmread(open(infile1, 'r'))
220
221 header = 'infer' if params['input_options']['header2'] else None
222 column_option = (params['input_options']['column_selector_options_2']
223 ['selected_column_selector_option2'])
224 if column_option in ['by_index_number', 'all_but_by_index_number',
225 'by_header_name', 'all_but_by_header_name']:
226 c = params['input_options']['column_selector_options_2']['col2']
227 else:
228 c = None
229 y = read_columns(
230 infile2,
231 c=c,
232 c_option=column_option,
233 sep='\t',
234 header=header,
235 parse_dates=True)
236 y = y.ravel()
237
238 optimizer = params['search_schemes']['selected_search_scheme']
239 optimizer = getattr(model_selection, optimizer)
240
241 options = params['search_schemes']['options']
242
243 splitter, groups = get_cv(options.pop('cv_selector'))
244 options['cv'] = splitter
245 options['n_jobs'] = N_JOBS
246 primary_scoring = options['scoring']['primary_scoring']
247 options['scoring'] = get_scoring(options['scoring'])
248 if options['error_score']:
249 options['error_score'] = 'raise'
250 else:
251 options['error_score'] = np.NaN
252 if options['refit'] and isinstance(options['scoring'], dict):
253 options['refit'] = primary_scoring
254 if 'pre_dispatch' in options and options['pre_dispatch'] == '':
255 options['pre_dispatch'] = None
256
257 with open(infile_estimator, 'rb') as estimator_handler:
258 estimator = load_model(estimator_handler)
259
260 memory = joblib.Memory(location=CACHE_DIR, verbose=0)
261 # cache iraps_core fits could increase search speed significantly
262 if estimator.__class__.__name__ == 'IRAPSClassifier':
263 estimator.set_params(memory=memory)
264 else:
265 for p, v in estimator.get_params().items():
266 if p.endswith('memory'):
267 if len(p) > 8 and p[:-8].endswith('irapsclassifier'):
268 # cache iraps_core fits could increase search
269 # speed significantly
270 new_params = {p: memory}
271 estimator.set_params(**new_params)
272 elif v:
273 new_params = {p, None}
274 estimator.set_params(**new_params)
275 elif p.endswith('n_jobs'):
276 new_params = {p: 1}
277 estimator.set_params(**new_params)
278
279 param_grid = _eval_search_params(params_builder)
280 searcher = optimizer(estimator, param_grid, **options)
281
282 # do train_test_split
283 do_train_test_split = params['train_test_split'].pop('do_split')
284 if do_train_test_split == 'yes':
285 # make sure refit is choosen
286 if not options['refit']:
287 raise ValueError("Refit must be `True` for shuffle splitting!")
288 split_options = params['train_test_split']
289
290 # splits
291 if split_options['shuffle'] == 'stratified':
292 split_options['labels'] = y
293 X, X_test, y, y_test = train_test_split(X, y, **split_options)
294 elif split_options['shuffle'] == 'group':
295 if not groups:
296 raise ValueError("No group based CV option was "
297 "choosen for group shuffle!")
298 split_options['labels'] = groups
299 X, X_test, y, y_test, groups, _ =\
300 train_test_split(X, y, **split_options)
301 else:
302 if split_options['shuffle'] == 'None':
303 split_options['shuffle'] = None
304 X, X_test, y, y_test =\
305 train_test_split(X, y, **split_options)
306 # end train_test_split
307
308 if options['error_score'] == 'raise':
309 searcher.fit(X, y, groups=groups)
310 else:
311 warnings.simplefilter('always', FitFailedWarning)
312 with warnings.catch_warnings(record=True) as w:
313 try:
314 searcher.fit(X, y, groups=groups)
315 except ValueError:
316 pass
317 for warning in w:
318 print(repr(warning.message))
319
320 if do_train_test_split == 'no':
321 # save results
322 cv_results = pandas.DataFrame(searcher.cv_results_)
323 cv_results = cv_results[sorted(cv_results.columns)]
324 cv_results.to_csv(path_or_buf=outfile_result, sep='\t',
325 header=True, index=False)
326
327 # output test result using best_estimator_
328 else:
329 best_estimator_ = searcher.best_estimator_
330 if isinstance(options['scoring'], collections.Mapping):
331 is_multimetric = True
332 else:
333 is_multimetric = False
334
335 test_score = _score(best_estimator_, X_test,
336 y_test, options['scoring'],
337 is_multimetric=is_multimetric)
338 if not is_multimetric:
339 test_score = {primary_scoring: test_score}
340 for key, value in test_score.items():
341 test_score[key] = [value]
342 result_df = pandas.DataFrame(test_score)
343 result_df.to_csv(path_or_buf=outfile_result, sep='\t',
344 header=True, index=False)
345
346 memory.clear(warn=False)
347
348 if outfile_object:
349 with open(outfile_object, 'wb') as output_handler:
350 pickle.dump(searcher, output_handler, pickle.HIGHEST_PROTOCOL)
351
352
353 if __name__ == '__main__':
354 aparser = argparse.ArgumentParser()
355 aparser.add_argument("-i", "--inputs", dest="inputs", required=True)
356 aparser.add_argument("-e", "--estimator", dest="infile_estimator")
357 aparser.add_argument("-X", "--infile1", dest="infile1")
358 aparser.add_argument("-y", "--infile2", dest="infile2")
359 aparser.add_argument("-r", "--outfile_result", dest="outfile_result")
360 aparser.add_argument("-o", "--outfile_object", dest="outfile_object")
361 aparser.add_argument("-g", "--groups", dest="groups")
362 args = aparser.parse_args()
363
364 main(args.inputs, args.infile_estimator, args.infile1, args.infile2,
365 args.outfile_result, outfile_object=args.outfile_object,
366 groups=args.groups)