Mercurial > repos > bgruening > sklearn_stacking_ensemble_models
comparison search_model_validation.py @ 7:00819b7f2f55 draft
"planemo upload for repository https://github.com/bgruening/galaxytools/tree/master/tools/sklearn commit 756f8be9c3cd437e131e6410cd625c24fe078e8c"
| author | bgruening |
|---|---|
| date | Wed, 22 Jan 2020 12:33:01 +0000 |
| parents | 963e449636d3 |
| children | b8c92e94ac1d |
comparison
equal
deleted
inserted
replaced
| 6:aae4725f152b | 7:00819b7f2f55 |
|---|---|
| 2 import collections | 2 import collections |
| 3 import imblearn | 3 import imblearn |
| 4 import joblib | 4 import joblib |
| 5 import json | 5 import json |
| 6 import numpy as np | 6 import numpy as np |
| 7 import os | |
| 7 import pandas as pd | 8 import pandas as pd |
| 8 import pickle | 9 import pickle |
| 9 import skrebate | 10 import skrebate |
| 10 import sklearn | |
| 11 import sys | 11 import sys |
| 12 import xgboost | |
| 13 import warnings | 12 import warnings |
| 14 from imblearn import under_sampling, over_sampling, combine | |
| 15 from scipy.io import mmread | 13 from scipy.io import mmread |
| 16 from mlxtend import classifier, regressor | 14 from sklearn import (cluster, decomposition, feature_selection, |
| 17 from sklearn.base import clone | 15 kernel_approximation, model_selection, preprocessing) |
| 18 from sklearn import (cluster, compose, decomposition, ensemble, | |
| 19 feature_extraction, feature_selection, | |
| 20 gaussian_process, kernel_approximation, metrics, | |
| 21 model_selection, naive_bayes, neighbors, | |
| 22 pipeline, preprocessing, svm, linear_model, | |
| 23 tree, discriminant_analysis) | |
| 24 from sklearn.exceptions import FitFailedWarning | 16 from sklearn.exceptions import FitFailedWarning |
| 25 from sklearn.model_selection._validation import _score, cross_validate | 17 from sklearn.model_selection._validation import _score, cross_validate |
| 26 from sklearn.model_selection import _search, _validation | 18 from sklearn.model_selection import _search, _validation |
| 19 from sklearn.pipeline import Pipeline | |
| 27 | 20 |
| 28 from galaxy_ml.utils import (SafeEval, get_cv, get_scoring, load_model, | 21 from galaxy_ml.utils import (SafeEval, get_cv, get_scoring, load_model, |
| 29 read_columns, try_get_attr, get_module) | 22 read_columns, try_get_attr, get_module, |
| 23 clean_params, get_main_estimator) | |
| 30 | 24 |
| 31 | 25 |
| 32 _fit_and_score = try_get_attr('galaxy_ml.model_validations', '_fit_and_score') | 26 _fit_and_score = try_get_attr('galaxy_ml.model_validations', '_fit_and_score') |
| 33 setattr(_search, '_fit_and_score', _fit_and_score) | 27 setattr(_search, '_fit_and_score', _fit_and_score) |
| 34 setattr(_validation, '_fit_and_score', _fit_and_score) | 28 setattr(_validation, '_fit_and_score', _fit_and_score) |
| 35 | 29 |
| 36 N_JOBS = int(__import__('os').environ.get('GALAXY_SLOTS', 1)) | 30 N_JOBS = int(os.environ.get('GALAXY_SLOTS', 1)) |
| 37 CACHE_DIR = './cached' | 31 # handle disk cache |
| 32 CACHE_DIR = os.path.join(os.getcwd(), 'cached') | |
| 33 del os | |
| 38 NON_SEARCHABLE = ('n_jobs', 'pre_dispatch', 'memory', '_path', | 34 NON_SEARCHABLE = ('n_jobs', 'pre_dispatch', 'memory', '_path', |
| 39 'nthread', 'callbacks') | 35 'nthread', 'callbacks') |
| 40 ALLOWED_CALLBACKS = ('EarlyStopping', 'TerminateOnNaN', 'ReduceLROnPlateau', | |
| 41 'CSVLogger', 'None') | |
| 42 | 36 |
| 43 | 37 |
| 44 def _eval_search_params(params_builder): | 38 def _eval_search_params(params_builder): |
| 45 search_params = {} | 39 search_params = {} |
| 46 | 40 |
| 162 search_params[param_name] = newlist | 156 search_params[param_name] = newlist |
| 163 | 157 |
| 164 return search_params | 158 return search_params |
| 165 | 159 |
| 166 | 160 |
| 167 def main(inputs, infile_estimator, infile1, infile2, | 161 def _handle_X_y(estimator, params, infile1, infile2, loaded_df={}, |
| 168 outfile_result, outfile_object=None, | 162 ref_seq=None, intervals=None, targets=None, |
| 169 outfile_weights=None, groups=None, | 163 fasta_path=None): |
| 170 ref_seq=None, intervals=None, targets=None, | 164 """read inputs |
| 171 fasta_path=None): | 165 |
| 172 """ | 166 Params |
| 173 Parameter | 167 ------- |
| 174 --------- | 168 estimator : estimator object |
| 175 inputs : str | 169 params : dict |
| 176 File path to galaxy tool parameter | 170 Galaxy tool parameter inputs |
| 177 | |
| 178 infile_estimator : str | |
| 179 File path to estimator | |
| 180 | |
| 181 infile1 : str | 171 infile1 : str |
| 182 File path to dataset containing features | 172 File path to dataset containing features |
| 183 | |
| 184 infile2 : str | 173 infile2 : str |
| 185 File path to dataset containing target values | 174 File path to dataset containing target values |
| 186 | 175 loaded_df : dict |
| 187 outfile_result : str | 176 Contains loaded DataFrame objects with file path as keys |
| 188 File path to save the results, either cv_results or test result | |
| 189 | |
| 190 outfile_object : str, optional | |
| 191 File path to save searchCV object | |
| 192 | |
| 193 outfile_weights : str, optional | |
| 194 File path to save model weights | |
| 195 | |
| 196 groups : str | |
| 197 File path to dataset containing groups labels | |
| 198 | |
| 199 ref_seq : str | 177 ref_seq : str |
| 200 File path to dataset containing genome sequence file | 178 File path to dataset containing genome sequence file |
| 201 | 179 interval : str |
| 202 intervals : str | |
| 203 File path to dataset containing interval file | 180 File path to dataset containing interval file |
| 204 | |
| 205 targets : str | 181 targets : str |
| 206 File path to dataset compressed target bed file | 182 File path to dataset compressed target bed file |
| 207 | |
| 208 fasta_path : str | 183 fasta_path : str |
| 209 File path to dataset containing fasta file | 184 File path to dataset containing fasta file |
| 185 | |
| 186 | |
| 187 Returns | |
| 188 ------- | |
| 189 estimator : estimator object after setting new attributes | |
| 190 X : numpy array | |
| 191 y : numpy array | |
| 210 """ | 192 """ |
| 211 warnings.simplefilter('ignore') | |
| 212 | |
| 213 with open(inputs, 'r') as param_handler: | |
| 214 params = json.load(param_handler) | |
| 215 | |
| 216 # conflict param checker | |
| 217 if params['outer_split']['split_mode'] == 'nested_cv' \ | |
| 218 and params['save'] != 'nope': | |
| 219 raise ValueError("Save best estimator is not possible for nested CV!") | |
| 220 | |
| 221 if not (params['search_schemes']['options']['refit']) \ | |
| 222 and params['save'] != 'nope': | |
| 223 raise ValueError("Save best estimator is not possible when refit " | |
| 224 "is False!") | |
| 225 | |
| 226 params_builder = params['search_schemes']['search_params_builder'] | |
| 227 | |
| 228 with open(infile_estimator, 'rb') as estimator_handler: | |
| 229 estimator = load_model(estimator_handler) | |
| 230 estimator_params = estimator.get_params() | 193 estimator_params = estimator.get_params() |
| 231 | |
| 232 # store read dataframe object | |
| 233 loaded_df = {} | |
| 234 | 194 |
| 235 input_type = params['input_options']['selected_input'] | 195 input_type = params['input_options']['selected_input'] |
| 236 # tabular input | 196 # tabular input |
| 237 if input_type == 'tabular': | 197 if input_type == 'tabular': |
| 238 header = 'infer' if params['input_options']['header1'] else None | 198 header = 'infer' if params['input_options']['header1'] else None |
| 243 c = params['input_options']['column_selector_options_1']['col1'] | 203 c = params['input_options']['column_selector_options_1']['col1'] |
| 244 else: | 204 else: |
| 245 c = None | 205 c = None |
| 246 | 206 |
| 247 df_key = infile1 + repr(header) | 207 df_key = infile1 + repr(header) |
| 208 | |
| 209 if df_key in loaded_df: | |
| 210 infile1 = loaded_df[df_key] | |
| 211 | |
| 248 df = pd.read_csv(infile1, sep='\t', header=header, | 212 df = pd.read_csv(infile1, sep='\t', header=header, |
| 249 parse_dates=True) | 213 parse_dates=True) |
| 250 loaded_df[df_key] = df | 214 loaded_df[df_key] = df |
| 251 | 215 |
| 252 X = read_columns(df, c=c, c_option=column_option).astype(float) | 216 X = read_columns(df, c=c, c_option=column_option).astype(float) |
| 315 estimator.set_params( | 279 estimator.set_params( |
| 316 data_batch_generator__features=y.ravel().tolist()) | 280 data_batch_generator__features=y.ravel().tolist()) |
| 317 y = None | 281 y = None |
| 318 # end y | 282 # end y |
| 319 | 283 |
| 284 return estimator, X, y | |
| 285 | |
| 286 | |
| 287 def _do_outer_cv(searcher, X, y, outer_cv, scoring, error_score='raise', | |
| 288 outfile=None): | |
| 289 """Do outer cross-validation for nested CV | |
| 290 | |
| 291 Parameters | |
| 292 ---------- | |
| 293 searcher : object | |
| 294 SearchCV object | |
| 295 X : numpy array | |
| 296 Containing features | |
| 297 y : numpy array | |
| 298 Target values or labels | |
| 299 outer_cv : int or CV splitter | |
| 300 Control the cv splitting | |
| 301 scoring : object | |
| 302 Scorer | |
| 303 error_score: str, float or numpy float | |
| 304 Whether to raise fit error or return an value | |
| 305 outfile : str | |
| 306 File path to store the restuls | |
| 307 """ | |
| 308 if error_score == 'raise': | |
| 309 rval = cross_validate( | |
| 310 searcher, X, y, scoring=scoring, | |
| 311 cv=outer_cv, n_jobs=N_JOBS, verbose=0, | |
| 312 error_score=error_score) | |
| 313 else: | |
| 314 warnings.simplefilter('always', FitFailedWarning) | |
| 315 with warnings.catch_warnings(record=True) as w: | |
| 316 try: | |
| 317 rval = cross_validate( | |
| 318 searcher, X, y, | |
| 319 scoring=scoring, | |
| 320 cv=outer_cv, n_jobs=N_JOBS, | |
| 321 verbose=0, | |
| 322 error_score=error_score) | |
| 323 except ValueError: | |
| 324 pass | |
| 325 for warning in w: | |
| 326 print(repr(warning.message)) | |
| 327 | |
| 328 keys = list(rval.keys()) | |
| 329 for k in keys: | |
| 330 if k.startswith('test'): | |
| 331 rval['mean_' + k] = np.mean(rval[k]) | |
| 332 rval['std_' + k] = np.std(rval[k]) | |
| 333 if k.endswith('time'): | |
| 334 rval.pop(k) | |
| 335 rval = pd.DataFrame(rval) | |
| 336 rval = rval[sorted(rval.columns)] | |
| 337 rval.to_csv(path_or_buf=outfile, sep='\t', header=True, index=False) | |
| 338 | |
| 339 | |
| 340 def _do_train_test_split_val(searcher, X, y, params, error_score='raise', | |
| 341 primary_scoring=None, groups=None, | |
| 342 outfile=None): | |
| 343 """ do train test split, searchCV validates on the train and then use | |
| 344 the best_estimator_ to evaluate on the test | |
| 345 | |
| 346 Returns | |
| 347 -------- | |
| 348 Fitted SearchCV object | |
| 349 """ | |
| 350 train_test_split = try_get_attr( | |
| 351 'galaxy_ml.model_validations', 'train_test_split') | |
| 352 split_options = params['outer_split'] | |
| 353 | |
| 354 # splits | |
| 355 if split_options['shuffle'] == 'stratified': | |
| 356 split_options['labels'] = y | |
| 357 X, X_test, y, y_test = train_test_split(X, y, **split_options) | |
| 358 elif split_options['shuffle'] == 'group': | |
| 359 if groups is None: | |
| 360 raise ValueError("No group based CV option was choosen for " | |
| 361 "group shuffle!") | |
| 362 split_options['labels'] = groups | |
| 363 if y is None: | |
| 364 X, X_test, groups, _ =\ | |
| 365 train_test_split(X, groups, **split_options) | |
| 366 else: | |
| 367 X, X_test, y, y_test, groups, _ =\ | |
| 368 train_test_split(X, y, groups, **split_options) | |
| 369 else: | |
| 370 if split_options['shuffle'] == 'None': | |
| 371 split_options['shuffle'] = None | |
| 372 X, X_test, y, y_test =\ | |
| 373 train_test_split(X, y, **split_options) | |
| 374 | |
| 375 if error_score == 'raise': | |
| 376 searcher.fit(X, y, groups=groups) | |
| 377 else: | |
| 378 warnings.simplefilter('always', FitFailedWarning) | |
| 379 with warnings.catch_warnings(record=True) as w: | |
| 380 try: | |
| 381 searcher.fit(X, y, groups=groups) | |
| 382 except ValueError: | |
| 383 pass | |
| 384 for warning in w: | |
| 385 print(repr(warning.message)) | |
| 386 | |
| 387 scorer_ = searcher.scorer_ | |
| 388 if isinstance(scorer_, collections.Mapping): | |
| 389 is_multimetric = True | |
| 390 else: | |
| 391 is_multimetric = False | |
| 392 | |
| 393 best_estimator_ = getattr(searcher, 'best_estimator_') | |
| 394 | |
| 395 # TODO Solve deep learning models in pipeline | |
| 396 if best_estimator_.__class__.__name__ == 'KerasGBatchClassifier': | |
| 397 test_score = best_estimator_.evaluate( | |
| 398 X_test, scorer=scorer_, is_multimetric=is_multimetric) | |
| 399 else: | |
| 400 test_score = _score(best_estimator_, X_test, | |
| 401 y_test, scorer_, | |
| 402 is_multimetric=is_multimetric) | |
| 403 | |
| 404 if not is_multimetric: | |
| 405 test_score = {primary_scoring: test_score} | |
| 406 for key, value in test_score.items(): | |
| 407 test_score[key] = [value] | |
| 408 result_df = pd.DataFrame(test_score) | |
| 409 result_df.to_csv(path_or_buf=outfile, sep='\t', header=True, | |
| 410 index=False) | |
| 411 | |
| 412 return searcher | |
| 413 | |
| 414 | |
| 415 def main(inputs, infile_estimator, infile1, infile2, | |
| 416 outfile_result, outfile_object=None, | |
| 417 outfile_weights=None, groups=None, | |
| 418 ref_seq=None, intervals=None, targets=None, | |
| 419 fasta_path=None): | |
| 420 """ | |
| 421 Parameter | |
| 422 --------- | |
| 423 inputs : str | |
| 424 File path to galaxy tool parameter | |
| 425 | |
| 426 infile_estimator : str | |
| 427 File path to estimator | |
| 428 | |
| 429 infile1 : str | |
| 430 File path to dataset containing features | |
| 431 | |
| 432 infile2 : str | |
| 433 File path to dataset containing target values | |
| 434 | |
| 435 outfile_result : str | |
| 436 File path to save the results, either cv_results or test result | |
| 437 | |
| 438 outfile_object : str, optional | |
| 439 File path to save searchCV object | |
| 440 | |
| 441 outfile_weights : str, optional | |
| 442 File path to save model weights | |
| 443 | |
| 444 groups : str | |
| 445 File path to dataset containing groups labels | |
| 446 | |
| 447 ref_seq : str | |
| 448 File path to dataset containing genome sequence file | |
| 449 | |
| 450 intervals : str | |
| 451 File path to dataset containing interval file | |
| 452 | |
| 453 targets : str | |
| 454 File path to dataset compressed target bed file | |
| 455 | |
| 456 fasta_path : str | |
| 457 File path to dataset containing fasta file | |
| 458 """ | |
| 459 warnings.simplefilter('ignore') | |
| 460 | |
| 461 # store read dataframe object | |
| 462 loaded_df = {} | |
| 463 | |
| 464 with open(inputs, 'r') as param_handler: | |
| 465 params = json.load(param_handler) | |
| 466 | |
| 467 # Override the refit parameter | |
| 468 params['search_schemes']['options']['refit'] = True \ | |
| 469 if params['save'] != 'nope' else False | |
| 470 | |
| 471 with open(infile_estimator, 'rb') as estimator_handler: | |
| 472 estimator = load_model(estimator_handler) | |
| 473 | |
| 320 optimizer = params['search_schemes']['selected_search_scheme'] | 474 optimizer = params['search_schemes']['selected_search_scheme'] |
| 321 optimizer = getattr(model_selection, optimizer) | 475 optimizer = getattr(model_selection, optimizer) |
| 322 | 476 |
| 323 # handle gridsearchcv options | 477 # handle gridsearchcv options |
| 324 options = params['search_schemes']['options'] | 478 options = params['search_schemes']['options'] |
| 335 ['column_selector_options_g']['col_g']) | 489 ['column_selector_options_g']['col_g']) |
| 336 else: | 490 else: |
| 337 c = None | 491 c = None |
| 338 | 492 |
| 339 df_key = groups + repr(header) | 493 df_key = groups + repr(header) |
| 340 if df_key in loaded_df: | 494 |
| 341 groups = loaded_df[df_key] | 495 groups = pd.read_csv(groups, sep='\t', header=header, |
| 496 parse_dates=True) | |
| 497 loaded_df[df_key] = groups | |
| 342 | 498 |
| 343 groups = read_columns( | 499 groups = read_columns( |
| 344 groups, | 500 groups, |
| 345 c=c, | 501 c=c, |
| 346 c_option=column_option, | 502 c_option=column_option, |
| 350 groups = groups.ravel() | 506 groups = groups.ravel() |
| 351 options['cv_selector']['groups_selector'] = groups | 507 options['cv_selector']['groups_selector'] = groups |
| 352 | 508 |
| 353 splitter, groups = get_cv(options.pop('cv_selector')) | 509 splitter, groups = get_cv(options.pop('cv_selector')) |
| 354 options['cv'] = splitter | 510 options['cv'] = splitter |
| 355 options['n_jobs'] = N_JOBS | |
| 356 primary_scoring = options['scoring']['primary_scoring'] | 511 primary_scoring = options['scoring']['primary_scoring'] |
| 357 options['scoring'] = get_scoring(options['scoring']) | 512 options['scoring'] = get_scoring(options['scoring']) |
| 358 if options['error_score']: | 513 if options['error_score']: |
| 359 options['error_score'] = 'raise' | 514 options['error_score'] = 'raise' |
| 360 else: | 515 else: |
| 362 if options['refit'] and isinstance(options['scoring'], dict): | 517 if options['refit'] and isinstance(options['scoring'], dict): |
| 363 options['refit'] = primary_scoring | 518 options['refit'] = primary_scoring |
| 364 if 'pre_dispatch' in options and options['pre_dispatch'] == '': | 519 if 'pre_dispatch' in options and options['pre_dispatch'] == '': |
| 365 options['pre_dispatch'] = None | 520 options['pre_dispatch'] = None |
| 366 | 521 |
| 367 # del loaded_df | 522 params_builder = params['search_schemes']['search_params_builder'] |
| 368 del loaded_df | 523 param_grid = _eval_search_params(params_builder) |
| 369 | 524 |
| 370 # handle memory | 525 estimator = clean_params(estimator) |
| 526 | |
| 527 # save the SearchCV object without fit | |
| 528 if params['save'] == 'save_no_fit': | |
| 529 searcher = optimizer(estimator, param_grid, **options) | |
| 530 print(searcher) | |
| 531 with open(outfile_object, 'wb') as output_handler: | |
| 532 pickle.dump(searcher, output_handler, | |
| 533 pickle.HIGHEST_PROTOCOL) | |
| 534 return 0 | |
| 535 | |
| 536 # read inputs and loads new attributes, like paths | |
| 537 estimator, X, y = _handle_X_y(estimator, params, infile1, infile2, | |
| 538 loaded_df=loaded_df, ref_seq=ref_seq, | |
| 539 intervals=intervals, targets=targets, | |
| 540 fasta_path=fasta_path) | |
| 541 | |
| 542 # cache iraps_core fits could increase search speed significantly | |
| 371 memory = joblib.Memory(location=CACHE_DIR, verbose=0) | 543 memory = joblib.Memory(location=CACHE_DIR, verbose=0) |
| 372 # cache iraps_core fits could increase search speed significantly | 544 main_est = get_main_estimator(estimator) |
| 373 if estimator.__class__.__name__ == 'IRAPSClassifier': | 545 if main_est.__class__.__name__ == 'IRAPSClassifier': |
| 374 estimator.set_params(memory=memory) | 546 main_est.set_params(memory=memory) |
| 375 else: | 547 |
| 376 # For iraps buried in pipeline | |
| 377 for p, v in estimator_params.items(): | |
| 378 if p.endswith('memory'): | |
| 379 # for case of `__irapsclassifier__memory` | |
| 380 if len(p) > 8 and p[:-8].endswith('irapsclassifier'): | |
| 381 # cache iraps_core fits could increase search | |
| 382 # speed significantly | |
| 383 new_params = {p: memory} | |
| 384 estimator.set_params(**new_params) | |
| 385 # security reason, we don't want memory being | |
| 386 # modified unexpectedly | |
| 387 elif v: | |
| 388 new_params = {p, None} | |
| 389 estimator.set_params(**new_params) | |
| 390 # For now, 1 CPU is suggested for iprasclassifier | |
| 391 elif p.endswith('n_jobs'): | |
| 392 new_params = {p: 1} | |
| 393 estimator.set_params(**new_params) | |
| 394 # for security reason, types of callbacks are limited | |
| 395 elif p.endswith('callbacks'): | |
| 396 for cb in v: | |
| 397 cb_type = cb['callback_selection']['callback_type'] | |
| 398 if cb_type not in ALLOWED_CALLBACKS: | |
| 399 raise ValueError( | |
| 400 "Prohibited callback type: %s!" % cb_type) | |
| 401 | |
| 402 param_grid = _eval_search_params(params_builder) | |
| 403 searcher = optimizer(estimator, param_grid, **options) | 548 searcher = optimizer(estimator, param_grid, **options) |
| 404 | 549 |
| 405 # do nested split | |
| 406 split_mode = params['outer_split'].pop('split_mode') | 550 split_mode = params['outer_split'].pop('split_mode') |
| 407 # nested CV, outer cv using cross_validate | 551 |
| 408 if split_mode == 'nested_cv': | 552 if split_mode == 'nested_cv': |
| 553 # make sure refit is choosen | |
| 554 # this could be True for sklearn models, but not the case for | |
| 555 # deep learning models | |
| 556 if not options['refit'] and \ | |
| 557 not all(hasattr(estimator, attr) | |
| 558 for attr in ('config', 'model_type')): | |
| 559 warnings.warn("Refit is change to `True` for nested validation!") | |
| 560 setattr(searcher, 'refit', True) | |
| 561 | |
| 409 outer_cv, _ = get_cv(params['outer_split']['cv_selector']) | 562 outer_cv, _ = get_cv(params['outer_split']['cv_selector']) |
| 410 | 563 # nested CV, outer cv using cross_validate |
| 411 if options['error_score'] == 'raise': | 564 if options['error_score'] == 'raise': |
| 412 rval = cross_validate( | 565 rval = cross_validate( |
| 413 searcher, X, y, scoring=options['scoring'], | 566 searcher, X, y, scoring=options['scoring'], |
| 414 cv=outer_cv, n_jobs=N_JOBS, verbose=0, | 567 cv=outer_cv, n_jobs=N_JOBS, |
| 415 error_score=options['error_score']) | 568 verbose=options['verbose'], |
| 569 return_estimator=(params['save'] == 'save_estimator'), | |
| 570 error_score=options['error_score'], | |
| 571 return_train_score=True) | |
| 416 else: | 572 else: |
| 417 warnings.simplefilter('always', FitFailedWarning) | 573 warnings.simplefilter('always', FitFailedWarning) |
| 418 with warnings.catch_warnings(record=True) as w: | 574 with warnings.catch_warnings(record=True) as w: |
| 419 try: | 575 try: |
| 420 rval = cross_validate( | 576 rval = cross_validate( |
| 421 searcher, X, y, | 577 searcher, X, y, |
| 422 scoring=options['scoring'], | 578 scoring=options['scoring'], |
| 423 cv=outer_cv, n_jobs=N_JOBS, | 579 cv=outer_cv, n_jobs=N_JOBS, |
| 424 verbose=0, | 580 verbose=options['verbose'], |
| 425 error_score=options['error_score']) | 581 return_estimator=(params['save'] == 'save_estimator'), |
| 582 error_score=options['error_score'], | |
| 583 return_train_score=True) | |
| 426 except ValueError: | 584 except ValueError: |
| 427 pass | 585 pass |
| 428 for warning in w: | 586 for warning in w: |
| 429 print(repr(warning.message)) | 587 print(repr(warning.message)) |
| 588 | |
| 589 fitted_searchers = rval.pop('estimator', []) | |
| 590 if fitted_searchers: | |
| 591 import os | |
| 592 pwd = os.getcwd() | |
| 593 save_dir = os.path.join(pwd, 'cv_results_in_folds') | |
| 594 try: | |
| 595 os.mkdir(save_dir) | |
| 596 for idx, obj in enumerate(fitted_searchers): | |
| 597 target_name = 'cv_results_' + '_' + 'split%d' % idx | |
| 598 target_path = os.path.join(pwd, save_dir, target_name) | |
| 599 cv_results_ = getattr(obj, 'cv_results_', None) | |
| 600 if not cv_results_: | |
| 601 print("%s is not available" % target_name) | |
| 602 continue | |
| 603 cv_results_ = pd.DataFrame(cv_results_) | |
| 604 cv_results_ = cv_results_[sorted(cv_results_.columns)] | |
| 605 cv_results_.to_csv(target_path, sep='\t', header=True, | |
| 606 index=False) | |
| 607 except Exception as e: | |
| 608 print(e) | |
| 609 finally: | |
| 610 del os | |
| 430 | 611 |
| 431 keys = list(rval.keys()) | 612 keys = list(rval.keys()) |
| 432 for k in keys: | 613 for k in keys: |
| 433 if k.startswith('test'): | 614 if k.startswith('test'): |
| 434 rval['mean_' + k] = np.mean(rval[k]) | 615 rval['mean_' + k] = np.mean(rval[k]) |
| 435 rval['std_' + k] = np.std(rval[k]) | 616 rval['std_' + k] = np.std(rval[k]) |
| 436 if k.endswith('time'): | 617 if k.endswith('time'): |
| 437 rval.pop(k) | 618 rval.pop(k) |
| 438 rval = pd.DataFrame(rval) | 619 rval = pd.DataFrame(rval) |
| 439 rval = rval[sorted(rval.columns)] | 620 rval = rval[sorted(rval.columns)] |
| 440 rval.to_csv(path_or_buf=outfile_result, sep='\t', | 621 rval.to_csv(path_or_buf=outfile_result, sep='\t', header=True, |
| 441 header=True, index=False) | 622 index=False) |
| 442 else: | 623 |
| 443 if split_mode == 'train_test_split': | 624 return 0 |
| 444 train_test_split = try_get_attr( | 625 |
| 445 'galaxy_ml.model_validations', 'train_test_split') | 626 # deprecate train test split mode |
| 446 # make sure refit is choosen | 627 """searcher = _do_train_test_split_val( |
| 447 # this could be True for sklearn models, but not the case for | 628 searcher, X, y, params, |
| 448 # deep learning models | 629 primary_scoring=primary_scoring, |
| 449 if not options['refit'] and \ | 630 error_score=options['error_score'], |
| 450 not all(hasattr(estimator, attr) | 631 groups=groups, |
| 451 for attr in ('config', 'model_type')): | 632 outfile=outfile_result)""" |
| 452 warnings.warn("Refit is change to `True` for nested " | 633 |
| 453 "validation!") | 634 # no outer split |
| 454 setattr(searcher, 'refit', True) | 635 else: |
| 455 split_options = params['outer_split'] | 636 searcher.set_params(n_jobs=N_JOBS) |
| 456 | |
| 457 # splits | |
| 458 if split_options['shuffle'] == 'stratified': | |
| 459 split_options['labels'] = y | |
| 460 X, X_test, y, y_test = train_test_split(X, y, **split_options) | |
| 461 elif split_options['shuffle'] == 'group': | |
| 462 if groups is None: | |
| 463 raise ValueError("No group based CV option was " | |
| 464 "choosen for group shuffle!") | |
| 465 split_options['labels'] = groups | |
| 466 if y is None: | |
| 467 X, X_test, groups, _ =\ | |
| 468 train_test_split(X, groups, **split_options) | |
| 469 else: | |
| 470 X, X_test, y, y_test, groups, _ =\ | |
| 471 train_test_split(X, y, groups, **split_options) | |
| 472 else: | |
| 473 if split_options['shuffle'] == 'None': | |
| 474 split_options['shuffle'] = None | |
| 475 X, X_test, y, y_test =\ | |
| 476 train_test_split(X, y, **split_options) | |
| 477 # end train_test_split | |
| 478 | |
| 479 # shared by both train_test_split and non-split | |
| 480 if options['error_score'] == 'raise': | 637 if options['error_score'] == 'raise': |
| 481 searcher.fit(X, y, groups=groups) | 638 searcher.fit(X, y, groups=groups) |
| 482 else: | 639 else: |
| 483 warnings.simplefilter('always', FitFailedWarning) | 640 warnings.simplefilter('always', FitFailedWarning) |
| 484 with warnings.catch_warnings(record=True) as w: | 641 with warnings.catch_warnings(record=True) as w: |
| 487 except ValueError: | 644 except ValueError: |
| 488 pass | 645 pass |
| 489 for warning in w: | 646 for warning in w: |
| 490 print(repr(warning.message)) | 647 print(repr(warning.message)) |
| 491 | 648 |
| 492 # no outer split | 649 cv_results = pd.DataFrame(searcher.cv_results_) |
| 493 if split_mode == 'no': | 650 cv_results = cv_results[sorted(cv_results.columns)] |
| 494 # save results | 651 cv_results.to_csv(path_or_buf=outfile_result, sep='\t', |
| 495 cv_results = pd.DataFrame(searcher.cv_results_) | 652 header=True, index=False) |
| 496 cv_results = cv_results[sorted(cv_results.columns)] | |
| 497 cv_results.to_csv(path_or_buf=outfile_result, sep='\t', | |
| 498 header=True, index=False) | |
| 499 | |
| 500 # train_test_split, output test result using best_estimator_ | |
| 501 # or rebuild the trained estimator using weights if applicable. | |
| 502 else: | |
| 503 scorer_ = searcher.scorer_ | |
| 504 if isinstance(scorer_, collections.Mapping): | |
| 505 is_multimetric = True | |
| 506 else: | |
| 507 is_multimetric = False | |
| 508 | |
| 509 best_estimator_ = getattr(searcher, 'best_estimator_', None) | |
| 510 if not best_estimator_: | |
| 511 raise ValueError("GridSearchCV object has no " | |
| 512 "`best_estimator_` when `refit`=False!") | |
| 513 | |
| 514 if best_estimator_.__class__.__name__ == 'KerasGBatchClassifier' \ | |
| 515 and hasattr(estimator.data_batch_generator, 'target_path'): | |
| 516 test_score = best_estimator_.evaluate( | |
| 517 X_test, scorer=scorer_, is_multimetric=is_multimetric) | |
| 518 else: | |
| 519 test_score = _score(best_estimator_, X_test, | |
| 520 y_test, scorer_, | |
| 521 is_multimetric=is_multimetric) | |
| 522 | |
| 523 if not is_multimetric: | |
| 524 test_score = {primary_scoring: test_score} | |
| 525 for key, value in test_score.items(): | |
| 526 test_score[key] = [value] | |
| 527 result_df = pd.DataFrame(test_score) | |
| 528 result_df.to_csv(path_or_buf=outfile_result, sep='\t', | |
| 529 header=True, index=False) | |
| 530 | 653 |
| 531 memory.clear(warn=False) | 654 memory.clear(warn=False) |
| 532 | 655 |
| 656 # output best estimator, and weights if applicable | |
| 533 if outfile_object: | 657 if outfile_object: |
| 534 best_estimator_ = getattr(searcher, 'best_estimator_', None) | 658 best_estimator_ = getattr(searcher, 'best_estimator_', None) |
| 535 if not best_estimator_: | 659 if not best_estimator_: |
| 536 warnings.warn("GridSearchCV object has no attribute " | 660 warnings.warn("GridSearchCV object has no attribute " |
| 537 "'best_estimator_', because either it's " | 661 "'best_estimator_', because either it's " |
| 538 "nested gridsearch or `refit` is False!") | 662 "nested gridsearch or `refit` is False!") |
| 539 return | 663 return |
| 540 | 664 |
| 541 main_est = best_estimator_ | 665 # clean prams |
| 542 if isinstance(best_estimator_, pipeline.Pipeline): | 666 best_estimator_ = clean_params(best_estimator_) |
| 543 main_est = best_estimator_.steps[-1][-1] | 667 |
| 668 main_est = get_main_estimator(best_estimator_) | |
| 544 | 669 |
| 545 if hasattr(main_est, 'model_') \ | 670 if hasattr(main_est, 'model_') \ |
| 546 and hasattr(main_est, 'save_weights'): | 671 and hasattr(main_est, 'save_weights'): |
| 547 if outfile_weights: | 672 if outfile_weights: |
| 548 main_est.save_weights(outfile_weights) | 673 main_est.save_weights(outfile_weights) |
| 552 del main_est.validation_data | 677 del main_est.validation_data |
| 553 if getattr(main_est, 'data_generator_', None): | 678 if getattr(main_est, 'data_generator_', None): |
| 554 del main_est.data_generator_ | 679 del main_est.data_generator_ |
| 555 | 680 |
| 556 with open(outfile_object, 'wb') as output_handler: | 681 with open(outfile_object, 'wb') as output_handler: |
| 682 print("Best estimator is saved: %s " % repr(best_estimator_)) | |
| 557 pickle.dump(best_estimator_, output_handler, | 683 pickle.dump(best_estimator_, output_handler, |
| 558 pickle.HIGHEST_PROTOCOL) | 684 pickle.HIGHEST_PROTOCOL) |
| 559 | 685 |
| 560 | 686 |
| 561 if __name__ == '__main__': | 687 if __name__ == '__main__': |
