comparison train_test_eval.py @ 0:03f61bb3ca43 draft

"planemo upload for repository https://github.com/bgruening/galaxytools/tree/master/tools/sklearn commit 5b2ac730ec6d3b762faa9034eddd19ad1b347476"
author bgruening
date Mon, 16 Dec 2019 05:36:53 -0500
parents
children 3866911c93ae
comparison
equal deleted inserted replaced
-1:000000000000 0:03f61bb3ca43
1 import argparse
2 import joblib
3 import json
4 import numpy as np
5 import os
6 import pandas as pd
7 import pickle
8 import warnings
9 from itertools import chain
10 from scipy.io import mmread
11 from sklearn.base import clone
12 from sklearn import (cluster, compose, decomposition, ensemble,
13 feature_extraction, feature_selection,
14 gaussian_process, kernel_approximation, metrics,
15 model_selection, naive_bayes, neighbors,
16 pipeline, preprocessing, svm, linear_model,
17 tree, discriminant_analysis)
18 from sklearn.exceptions import FitFailedWarning
19 from sklearn.metrics.scorer import _check_multimetric_scoring
20 from sklearn.model_selection._validation import _score, cross_validate
21 from sklearn.model_selection import _search, _validation
22 from sklearn.utils import indexable, safe_indexing
23
24 from galaxy_ml.model_validations import train_test_split
25 from galaxy_ml.utils import (SafeEval, get_scoring, load_model,
26 read_columns, try_get_attr, get_module)
27
28
29 _fit_and_score = try_get_attr('galaxy_ml.model_validations', '_fit_and_score')
30 setattr(_search, '_fit_and_score', _fit_and_score)
31 setattr(_validation, '_fit_and_score', _fit_and_score)
32
33 N_JOBS = int(os.environ.get('GALAXY_SLOTS', 1))
34 CACHE_DIR = os.path.join(os.getcwd(), 'cached')
35 del os
36 NON_SEARCHABLE = ('n_jobs', 'pre_dispatch', 'memory', '_path',
37 'nthread', 'callbacks')
38 ALLOWED_CALLBACKS = ('EarlyStopping', 'TerminateOnNaN', 'ReduceLROnPlateau',
39 'CSVLogger', 'None')
40
41
42 def _eval_swap_params(params_builder):
43 swap_params = {}
44
45 for p in params_builder['param_set']:
46 swap_value = p['sp_value'].strip()
47 if swap_value == '':
48 continue
49
50 param_name = p['sp_name']
51 if param_name.lower().endswith(NON_SEARCHABLE):
52 warnings.warn("Warning: `%s` is not eligible for search and was "
53 "omitted!" % param_name)
54 continue
55
56 if not swap_value.startswith(':'):
57 safe_eval = SafeEval(load_scipy=True, load_numpy=True)
58 ev = safe_eval(swap_value)
59 else:
60 # Have `:` before search list, asks for estimator evaluatio
61 safe_eval_es = SafeEval(load_estimators=True)
62 swap_value = swap_value[1:].strip()
63 # TODO maybe add regular express check
64 ev = safe_eval_es(swap_value)
65
66 swap_params[param_name] = ev
67
68 return swap_params
69
70
71 def train_test_split_none(*arrays, **kwargs):
72 """extend train_test_split to take None arrays
73 and support split by group names.
74 """
75 nones = []
76 new_arrays = []
77 for idx, arr in enumerate(arrays):
78 if arr is None:
79 nones.append(idx)
80 else:
81 new_arrays.append(arr)
82
83 if kwargs['shuffle'] == 'None':
84 kwargs['shuffle'] = None
85
86 group_names = kwargs.pop('group_names', None)
87
88 if group_names is not None and group_names.strip():
89 group_names = [name.strip() for name in
90 group_names.split(',')]
91 new_arrays = indexable(*new_arrays)
92 groups = kwargs['labels']
93 n_samples = new_arrays[0].shape[0]
94 index_arr = np.arange(n_samples)
95 test = index_arr[np.isin(groups, group_names)]
96 train = index_arr[~np.isin(groups, group_names)]
97 rval = list(chain.from_iterable(
98 (safe_indexing(a, train),
99 safe_indexing(a, test)) for a in new_arrays))
100 else:
101 rval = train_test_split(*new_arrays, **kwargs)
102
103 for pos in nones:
104 rval[pos * 2: 2] = [None, None]
105
106 return rval
107
108
109 def main(inputs, infile_estimator, infile1, infile2,
110 outfile_result, outfile_object=None,
111 outfile_weights=None, groups=None,
112 ref_seq=None, intervals=None, targets=None,
113 fasta_path=None):
114 """
115 Parameter
116 ---------
117 inputs : str
118 File path to galaxy tool parameter
119
120 infile_estimator : str
121 File path to estimator
122
123 infile1 : str
124 File path to dataset containing features
125
126 infile2 : str
127 File path to dataset containing target values
128
129 outfile_result : str
130 File path to save the results, either cv_results or test result
131
132 outfile_object : str, optional
133 File path to save searchCV object
134
135 outfile_weights : str, optional
136 File path to save deep learning model weights
137
138 groups : str
139 File path to dataset containing groups labels
140
141 ref_seq : str
142 File path to dataset containing genome sequence file
143
144 intervals : str
145 File path to dataset containing interval file
146
147 targets : str
148 File path to dataset compressed target bed file
149
150 fasta_path : str
151 File path to dataset containing fasta file
152 """
153 warnings.simplefilter('ignore')
154
155 with open(inputs, 'r') as param_handler:
156 params = json.load(param_handler)
157
158 # load estimator
159 with open(infile_estimator, 'rb') as estimator_handler:
160 estimator = load_model(estimator_handler)
161
162 # swap hyperparameter
163 swapping = params['experiment_schemes']['hyperparams_swapping']
164 swap_params = _eval_swap_params(swapping)
165 estimator.set_params(**swap_params)
166
167 estimator_params = estimator.get_params()
168
169 # store read dataframe object
170 loaded_df = {}
171
172 input_type = params['input_options']['selected_input']
173 # tabular input
174 if input_type == 'tabular':
175 header = 'infer' if params['input_options']['header1'] else None
176 column_option = (params['input_options']['column_selector_options_1']
177 ['selected_column_selector_option'])
178 if column_option in ['by_index_number', 'all_but_by_index_number',
179 'by_header_name', 'all_but_by_header_name']:
180 c = params['input_options']['column_selector_options_1']['col1']
181 else:
182 c = None
183
184 df_key = infile1 + repr(header)
185 df = pd.read_csv(infile1, sep='\t', header=header,
186 parse_dates=True)
187 loaded_df[df_key] = df
188
189 X = read_columns(df, c=c, c_option=column_option).astype(float)
190 # sparse input
191 elif input_type == 'sparse':
192 X = mmread(open(infile1, 'r'))
193
194 # fasta_file input
195 elif input_type == 'seq_fasta':
196 pyfaidx = get_module('pyfaidx')
197 sequences = pyfaidx.Fasta(fasta_path)
198 n_seqs = len(sequences.keys())
199 X = np.arange(n_seqs)[:, np.newaxis]
200 for param in estimator_params.keys():
201 if param.endswith('fasta_path'):
202 estimator.set_params(
203 **{param: fasta_path})
204 break
205 else:
206 raise ValueError(
207 "The selected estimator doesn't support "
208 "fasta file input! Please consider using "
209 "KerasGBatchClassifier with "
210 "FastaDNABatchGenerator/FastaProteinBatchGenerator "
211 "or having GenomeOneHotEncoder/ProteinOneHotEncoder "
212 "in pipeline!")
213
214 elif input_type == 'refseq_and_interval':
215 path_params = {
216 'data_batch_generator__ref_genome_path': ref_seq,
217 'data_batch_generator__intervals_path': intervals,
218 'data_batch_generator__target_path': targets
219 }
220 estimator.set_params(**path_params)
221 n_intervals = sum(1 for line in open(intervals))
222 X = np.arange(n_intervals)[:, np.newaxis]
223
224 # Get target y
225 header = 'infer' if params['input_options']['header2'] else None
226 column_option = (params['input_options']['column_selector_options_2']
227 ['selected_column_selector_option2'])
228 if column_option in ['by_index_number', 'all_but_by_index_number',
229 'by_header_name', 'all_but_by_header_name']:
230 c = params['input_options']['column_selector_options_2']['col2']
231 else:
232 c = None
233
234 df_key = infile2 + repr(header)
235 if df_key in loaded_df:
236 infile2 = loaded_df[df_key]
237 else:
238 infile2 = pd.read_csv(infile2, sep='\t',
239 header=header, parse_dates=True)
240 loaded_df[df_key] = infile2
241
242 y = read_columns(
243 infile2,
244 c=c,
245 c_option=column_option,
246 sep='\t',
247 header=header,
248 parse_dates=True)
249 if len(y.shape) == 2 and y.shape[1] == 1:
250 y = y.ravel()
251 if input_type == 'refseq_and_interval':
252 estimator.set_params(
253 data_batch_generator__features=y.ravel().tolist())
254 y = None
255 # end y
256
257 # load groups
258 if groups:
259 groups_selector = (params['experiment_schemes']['test_split']
260 ['split_algos']).pop('groups_selector')
261
262 header = 'infer' if groups_selector['header_g'] else None
263 column_option = \
264 (groups_selector['column_selector_options_g']
265 ['selected_column_selector_option_g'])
266 if column_option in ['by_index_number', 'all_but_by_index_number',
267 'by_header_name', 'all_but_by_header_name']:
268 c = groups_selector['column_selector_options_g']['col_g']
269 else:
270 c = None
271
272 df_key = groups + repr(header)
273 if df_key in loaded_df:
274 groups = loaded_df[df_key]
275
276 groups = read_columns(
277 groups,
278 c=c,
279 c_option=column_option,
280 sep='\t',
281 header=header,
282 parse_dates=True)
283 groups = groups.ravel()
284
285 # del loaded_df
286 del loaded_df
287
288 # handle memory
289 memory = joblib.Memory(location=CACHE_DIR, verbose=0)
290 # cache iraps_core fits could increase search speed significantly
291 if estimator.__class__.__name__ == 'IRAPSClassifier':
292 estimator.set_params(memory=memory)
293 else:
294 # For iraps buried in pipeline
295 new_params = {}
296 for p, v in estimator_params.items():
297 if p.endswith('memory'):
298 # for case of `__irapsclassifier__memory`
299 if len(p) > 8 and p[:-8].endswith('irapsclassifier'):
300 # cache iraps_core fits could increase search
301 # speed significantly
302 new_params[p] = memory
303 # security reason, we don't want memory being
304 # modified unexpectedly
305 elif v:
306 new_params[p] = None
307 # handle n_jobs
308 elif p.endswith('n_jobs'):
309 # For now, 1 CPU is suggested for iprasclassifier
310 if len(p) > 8 and p[:-8].endswith('irapsclassifier'):
311 new_params[p] = 1
312 else:
313 new_params[p] = N_JOBS
314 # for security reason, types of callback are limited
315 elif p.endswith('callbacks'):
316 for cb in v:
317 cb_type = cb['callback_selection']['callback_type']
318 if cb_type not in ALLOWED_CALLBACKS:
319 raise ValueError(
320 "Prohibited callback type: %s!" % cb_type)
321
322 estimator.set_params(**new_params)
323
324 # handle scorer, convert to scorer dict
325 scoring = params['experiment_schemes']['metrics']['scoring']
326 scorer = get_scoring(scoring)
327 scorer, _ = _check_multimetric_scoring(estimator, scoring=scorer)
328
329 # handle test (first) split
330 test_split_options = (params['experiment_schemes']
331 ['test_split']['split_algos'])
332
333 if test_split_options['shuffle'] == 'group':
334 test_split_options['labels'] = groups
335 if test_split_options['shuffle'] == 'stratified':
336 if y is not None:
337 test_split_options['labels'] = y
338 else:
339 raise ValueError("Stratified shuffle split is not "
340 "applicable on empty target values!")
341
342 X_train, X_test, y_train, y_test, groups_train, groups_test = \
343 train_test_split_none(X, y, groups, **test_split_options)
344
345 exp_scheme = params['experiment_schemes']['selected_exp_scheme']
346
347 # handle validation (second) split
348 if exp_scheme == 'train_val_test':
349 val_split_options = (params['experiment_schemes']
350 ['val_split']['split_algos'])
351
352 if val_split_options['shuffle'] == 'group':
353 val_split_options['labels'] = groups_train
354 if val_split_options['shuffle'] == 'stratified':
355 if y_train is not None:
356 val_split_options['labels'] = y_train
357 else:
358 raise ValueError("Stratified shuffle split is not "
359 "applicable on empty target values!")
360
361 X_train, X_val, y_train, y_val, groups_train, groups_val = \
362 train_test_split_none(X_train, y_train, groups_train,
363 **val_split_options)
364
365 # train and eval
366 if hasattr(estimator, 'validation_data'):
367 if exp_scheme == 'train_val_test':
368 estimator.fit(X_train, y_train,
369 validation_data=(X_val, y_val))
370 else:
371 estimator.fit(X_train, y_train,
372 validation_data=(X_test, y_test))
373 else:
374 estimator.fit(X_train, y_train)
375
376 if hasattr(estimator, 'evaluate'):
377 scores = estimator.evaluate(X_test, y_test=y_test,
378 scorer=scorer,
379 is_multimetric=True)
380 else:
381 scores = _score(estimator, X_test, y_test, scorer,
382 is_multimetric=True)
383 # handle output
384 for name, score in scores.items():
385 scores[name] = [score]
386 df = pd.DataFrame(scores)
387 df = df[sorted(df.columns)]
388 df.to_csv(path_or_buf=outfile_result, sep='\t',
389 header=True, index=False)
390
391 memory.clear(warn=False)
392
393 if outfile_object:
394 main_est = estimator
395 if isinstance(estimator, pipeline.Pipeline):
396 main_est = estimator.steps[-1][-1]
397
398 if hasattr(main_est, 'model_') \
399 and hasattr(main_est, 'save_weights'):
400 if outfile_weights:
401 main_est.save_weights(outfile_weights)
402 del main_est.model_
403 del main_est.fit_params
404 del main_est.model_class_
405 del main_est.validation_data
406 if getattr(main_est, 'data_generator_', None):
407 del main_est.data_generator_
408
409 with open(outfile_object, 'wb') as output_handler:
410 pickle.dump(estimator, output_handler,
411 pickle.HIGHEST_PROTOCOL)
412
413
414 if __name__ == '__main__':
415 aparser = argparse.ArgumentParser()
416 aparser.add_argument("-i", "--inputs", dest="inputs", required=True)
417 aparser.add_argument("-e", "--estimator", dest="infile_estimator")
418 aparser.add_argument("-X", "--infile1", dest="infile1")
419 aparser.add_argument("-y", "--infile2", dest="infile2")
420 aparser.add_argument("-O", "--outfile_result", dest="outfile_result")
421 aparser.add_argument("-o", "--outfile_object", dest="outfile_object")
422 aparser.add_argument("-w", "--outfile_weights", dest="outfile_weights")
423 aparser.add_argument("-g", "--groups", dest="groups")
424 aparser.add_argument("-r", "--ref_seq", dest="ref_seq")
425 aparser.add_argument("-b", "--intervals", dest="intervals")
426 aparser.add_argument("-t", "--targets", dest="targets")
427 aparser.add_argument("-f", "--fasta_path", dest="fasta_path")
428 args = aparser.parse_args()
429
430 main(args.inputs, args.infile_estimator, args.infile1, args.infile2,
431 args.outfile_result, outfile_object=args.outfile_object,
432 outfile_weights=args.outfile_weights, groups=args.groups,
433 ref_seq=args.ref_seq, intervals=args.intervals,
434 targets=args.targets, fasta_path=args.fasta_path)