HyperoptPipelineSelector.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Tue Oct 6 15:04:25 2020
  5. @author: tanya
  6. @description:a class for selecting a machine learning
  7. pipeline from a deterministic space of parameter distributions
  8. over multiple pipelines.
  9. The selection is though in such a way that a Trials object is being
  10. maintained during the tuning process from which one can retrieve
  11. the best pipeline so far as well as the entire tuning history
  12. if needed.
  13. """
  14. import os
  15. import sys
  16. import pickle
  17. from copy import deepcopy
  18. import datetime
  19. import pandas as pd
  20. import numpy as np
  21. from sklearn.pipeline import Pipeline
  22. from hyperopt import fmin, tpe, rand, Trials, space_eval
  23. from cdplib.pipeline_selector.PipelineSelector import PipelineSelector,\
  24. SpaceElementType
  25. # from typing import Callable, Optional, Literal, Dict, Union, List
  26. if (sys.version_info.major == 3) & (sys.version_info.minor >= 8):
  27. from typing import Callable, \
  28. Literal, Dict, List, Union
  29. else:
  30. # from typing_extensions import *
  31. from __future__ import annotations
  32. Dict = dict
  33. List = list
  34. from typing_extensions import Callable, \
  35. Literal, Dict, List, Union
  36. from cdplib.log import Log
  37. class HyperoptPipelineSelector(PipelineSelector):
  38. """
  39. Use this class to perform a search
  40. for a machine learning pipeline in a given parameter space.
  41. The parameter space can include multiple types of Pipelines
  42. (SVM, XGBOOST, random forest, etc),
  43. as well as parameter distributions for each pipeline parameter.
  44. See example in main for the expected space structure.
  45. The search can be performed either randomly
  46. or with a tree-based algorithm. (Other methods are currently
  47. developped by hyperopt creators).
  48. Attribute trials is responsible for book-keeping parameter
  49. combinations that have already been tried out. This attribute
  50. is saved to a binary file every n minutes as well as every time
  51. a better pipeline was found.
  52. """
  53. def __init__(self,
  54. cost_func: Union[Callable, str],
  55. greater_is_better: bool,
  56. trials_path: str,
  57. backup_trials_freq: Optional[int] = None,
  58. cross_validation_needs_scorer: bool = True,
  59. cross_val_averaging_func: Callable = np.mean,
  60. additional_metrics: Optional[Dict[str, Callable]] = None,
  61. strategy_name: Optional[str] = None,
  62. stdout_log_level: Literal["INFO", "WARNING", "ERROR"]
  63. = "INFO"):
  64. """
  65. param Callable cost_func: function to minimize or maximize
  66. over the elements of a given (pipeline/hyperparameter) space
  67. :param bool greater_is_better: when True
  68. cost_func is maximized, else minimized.
  69. :param str trials_path: path at which the trials object is saved
  70. in binary format. From the trials object we can
  71. select information about the obtained scores, score variations,
  72. and pipelines, and parameters tried out so far. If a trials object
  73. already exists at the given path, it is loaded and the
  74. search is continued, else, the search is started from scratch.
  75. :param backup_trials_freq: frequecy in interations (trials)
  76. of saving the trials object at the trials_path.
  77. if None, the trials object is backed up avery time
  78. the score improves.
  79. :param Callable cross_val_averaging_func: Function to aggregate
  80. the cross-validation scores.
  81. Example different from the mean: mean - c*var.
  82. :param additional_metics: dict of additional metrics to save
  83. of the form {"metric_name": metric} where metric is a Callable.
  84. :param str strategy_name:
  85. a strategy is defined by the data set (columns/features and rows),
  86. cv object, cost function.
  87. When the strategy changes, one must start with new trials.
  88. :param str stdout_log_level: can be INFO, WARNING, ERROR
  89. """
  90. try:
  91. super().__init__(cost_func=cost_func,
  92. greater_is_better=greater_is_better,
  93. trials_path=trials_path,
  94. backup_trials_freq=backup_trials_freq,
  95. cross_validation_needs_scorer=
  96. cross_validation_needs_scorer,
  97. cross_val_averaging_func=cross_val_averaging_func,
  98. additional_metrics=additional_metrics,
  99. strategy_name=strategy_name,
  100. stdout_log_level=stdout_log_level)
  101. self._logger = Log("HyperoptPipelineSelector: ",
  102. stdout_log_level=stdout_log_level)
  103. self._trials = self._trials or Trials()
  104. except Exception as e:
  105. err = "Failed to intialize. Exit with error: {}".format(e)
  106. self._logger.log_and_raise_error(err)
  107. def run_trials(self,
  108. niter: int,
  109. algo: Literal[tpe.suggest, rand.suggest] = tpe.suggest)\
  110. -> None:
  111. '''
  112. Method performing the search of the best pipeline in the given space.
  113. Calls fmin function from the hyperopt library to minimize the output of
  114. _objective.
  115. :params int niter: number of search iterations
  116. :param algo: now can only take supported by the hyperopt library.
  117. For now these are tpe.suggest for a tree-based bayesian search
  118. or rad.suggest for randomized search
  119. '''
  120. try:
  121. self._trials = self._trials or Trials()
  122. self._logger.info(("Starting {0} iterations of search "
  123. "additional to {1} previous"
  124. .format(niter, len(self._trials.trials))))
  125. best_trial = fmin(fn=self._objective,
  126. space=self._space,
  127. algo=algo,
  128. trials=self._trials,
  129. max_evals=len(self._trials.trials) + niter)
  130. self._logger.info(
  131. "Best score is {0} with variance {1}"
  132. .format(
  133. self._trials.best_trial["result"]["score"],
  134. self._trials.best_trial["result"]["score_variance"]))
  135. self._logger.info(("Finished {0} iterations of search.\n"
  136. "Best parameters are:\n {1} ")
  137. .format(niter,
  138. space_eval(self._space, best_trial)))
  139. self.finished_tuning = True
  140. self.total_tuning_time = datetime.datetime.today()\
  141. - self.start_tuning_time
  142. self._backup_trials()
  143. except Exception as e:
  144. err = ("Failed to select best "
  145. "pipeline! Exit with error: {}").format(e)
  146. self._logger.log_and_raise_error(err)
  147. @property
  148. def number_of_trials(self) -> Union[int, None]:
  149. """
  150. :return: number of trials run so far
  151. with the given Trials object
  152. """
  153. try:
  154. return len(self._trials.trials)
  155. except Exception as e:
  156. err = ("Failed to retrieve the number of trials. "
  157. "Exit with error {}".format(e))
  158. self._logger.log_and_raise_error(err)
  159. def _get_space_element_from_trial(self, trial: dict)\
  160. -> Union[Dict[str, SpaceElementType], None]:
  161. """
  162. Hyperopt trials object does not contain the space
  163. elements that result in the corresponding trials.
  164. One has to use the function space_eval from
  165. hyperopt to get the space element.
  166. After retrieving the space element,
  167. parameters of the pipeline are set.
  168. """
  169. try:
  170. trial = deepcopy(trial)
  171. assert(self.attached_space),\
  172. "Hyperparameter space not attached."
  173. space_element = space_eval(self._space,
  174. {k: v[0] for k, v in
  175. trial['misc']['vals'].items()
  176. if len(v) > 0})
  177. pipeline = deepcopy(space_element["pipeline"])
  178. params = deepcopy(space_element["params"])
  179. pipeline.set_params(**params)
  180. space_element["pipeline"] = pipeline
  181. return space_element
  182. except Exception as e:
  183. err = ("Failed to retrieve a space element from a trial. "
  184. "Exit with error: {}".format(e))
  185. self._logger.log_and_raise_error(err)
  186. def _get_space_element_from_index(self, i: int)\
  187. -> Union[Dict[str, SpaceElementType], None]:
  188. """
  189. Gets the space element of shape
  190. {"name": NAME, "params": PARAMS, "pipeline": PIPELINE}
  191. from the trial number i.
  192. """
  193. try:
  194. assert(len(self._trials.trials) > i),\
  195. ("Trials object is not long enough "
  196. "to retrieve index {}".format(i))
  197. return self._get_space_element_from_trial(self._trials.trials[i])
  198. except Exception as e:
  199. err = ("Failed to get space element from index. "
  200. "Exit with error {}".format(e))
  201. self._logger.log_and_raise_error(err)
  202. def _get_pipeline_from_index(self, i: int) -> Union[Pipeline, None]:
  203. """
  204. Gets a pipeline with set parameters from the trial number i
  205. """
  206. try:
  207. space_element = self._get_space_element_from_index(i)
  208. return space_element["pipeline"]
  209. except Exception as e:
  210. err = ("Failed to retrieve pipeline from index. "
  211. "Exit with error: {}".format(e))
  212. self._logger.log_and_raise_error(err)
  213. @property
  214. def best_trial(self) -> Union[dict, None]:
  215. """
  216. :return: dictionary with the summary of the best trial
  217. and space element (name, pipeline, params)
  218. resulting in the best trial
  219. """
  220. if len(self._trials.trials) == 0:
  221. self._logger.log_and_throw_warning("Trials object is empty")
  222. return {}
  223. else:
  224. try:
  225. best_trial = deepcopy(self._trials.best_trial)
  226. if self.attached_space:
  227. space_element = self._get_space_element_from_trial(
  228. best_trial)
  229. else:
  230. space_element = {}
  231. warn = ("Space is not attached, "
  232. "To included the best pipeline "
  233. "attach the space")
  234. self._logger.log_and_throw_warning(warn)
  235. best_trial = deepcopy(self._trials.best_trial["result"])
  236. best_trial.update(space_element)
  237. return best_trial
  238. except Exception as e:
  239. err = "Failed to retrieve best trial. Exit with error: {}"\
  240. .format(e)
  241. self._logger.log_and_raise_error(err)
  242. @property
  243. def best_trial_score(self) -> Union[float, None]:
  244. """
  245. """
  246. try:
  247. if len(self.best_trial) > 0:
  248. return self.best_trial["score"]
  249. else:
  250. return np.nan
  251. except Exception as e:
  252. err = ("Failed to retrieve best trial score. "
  253. "Exit with error: {}".format(e))
  254. self._logger.log_and_raise_error(err)
  255. @property
  256. def best_trial_score_variance(self) -> Union[float, None]:
  257. """
  258. """
  259. try:
  260. if len(self.best_trial) > 0:
  261. return self.best_trial["score_variance"]
  262. else:
  263. return np.nan
  264. except Exception as e:
  265. err = ("Failed to retrieve best trial score variance. "
  266. "Exit with error: {}".format(e))
  267. self._logger.log_and_raise_error(err)
  268. @property
  269. def best_trial_pipeline(self) -> Union[Pipeline, None]:
  270. """
  271. """
  272. try:
  273. if len(self.best_trial) > 0:
  274. return self.best_trial["pipeline"]
  275. else:
  276. return np.nan
  277. except Exception as e:
  278. err = ("Failed to retrieve best trial pipeline. "
  279. "Exit with error: {}".format(e))
  280. self._logger.log_and_raise_error(err)
  281. def get_n_best_trial(self, n: int)\
  282. -> Union[List[Pipeline], None]:
  283. """
  284. :return: the list of n best trails
  285. """
  286. try:
  287. if len(self._trials.trials) == 0:
  288. return []
  289. else:
  290. n_best_trials = sorted(self._trials.trials,
  291. key=lambda x: x["result"]["score"],
  292. reverse=True)[:n]
  293. return n_best_trials
  294. except Exception as e:
  295. err = ("Failed to retrieve n best pipelines. "
  296. "Exit with error: {}".format(e))
  297. self._logger.log_and_raise_error(err)
  298. def get_n_best_trial_pipelines(self, n: int)\
  299. -> Union[List[Pipeline], None]:
  300. """
  301. :return: the list of n best pipelines
  302. documented in trials
  303. """
  304. try:
  305. if len(self._trials.trials) == 0:
  306. return []
  307. else:
  308. n_best_trials = sorted(self._trials.trials,
  309. key=lambda x: x["result"]["score"],
  310. reverse=True)[:n]
  311. return [self._get_space_element_from_trial(trial)["pipeline"]
  312. for trial in n_best_trials]
  313. except Exception as e:
  314. err = ("Failed to retrieve n best pipelines. "
  315. "Exit with error: {}".format(e))
  316. self._logger.log_and_raise_error(err)
  317. def get_n_best_trial_pipelines_of_each_type(self, n: int)\
  318. -> Union[Dict[str, List[Pipeline]], None]:
  319. """
  320. :return: a dictiionry where keys are pipeline names,
  321. and values are lists of best pipelines with this name
  322. """
  323. try:
  324. scores = [trial["result"]["score"]
  325. for trial in self._trials.trials]
  326. names = [self._get_space_element_from_trial(trial)["name"]
  327. for trial in self._trials.trials]
  328. return pd.DataFrame({"name": names, "score": scores})\
  329. .sort_values(by=["name", "score"], ascending=False)\
  330. .groupby("name")\
  331. .head(n)\
  332. .reset_index()\
  333. .assign(pipeline=lambda x: x["index"]
  334. .apply(self._get_pipeline_from_index))\
  335. .groupby("name")["pipeline"]\
  336. .apply(lambda x: list(x))\
  337. .to_dict()
  338. except Exception as e:
  339. err = ("Failed to get n best pipelines of each type. "
  340. "Exit with error: {}".format(e))
  341. self._logger.log_and_raise_error(err)
  342. def trials_to_excel(self, path: str = None) -> None:
  343. """
  344. Saves an excel file with pipeline names, scores,
  345. parameters, and timestamps.
  346. """
  347. try:
  348. results = [trial["result"] for trial in self._trials.trials]
  349. space_elements = [self._get_space_element_from_trial(trial)
  350. for trial in self._trials.trials]
  351. pd.DataFrame([{**result, **space_element}
  352. for result, space_element in
  353. zip(results, space_elements)]).to_excel(path)
  354. except Exception as e:
  355. err = ("Failed to write trials to excel. "
  356. "Exit with error: {}".format(e))
  357. self._logger.log_and_raise_error(err)
  358. if __name__ == '__main__':
  359. # elementary example
  360. from sklearn.metrics import roc_auc_score, precision_score
  361. from sklearn.datasets import load_breast_cancer
  362. from cdplib.log import Log
  363. from cdplib.db_handlers import MongodbHandler
  364. from cdplib.hyperopt.space_sample import space
  365. # from cdplib.hyperopt.composed_space_sample import space
  366. trials_path = "hyperopt_trials_TEST.pkl"
  367. additional_metrics = {"precision": precision_score}
  368. strategy_name = "strategy_1"
  369. data_path = "data_TEST.h5"
  370. cv_path = "cv_TEST.pkl"
  371. collection_name = 'TEST_' + strategy_name
  372. logger = Log("HyperoptPipelineSelector__TEST:")
  373. logger.info("Start test")
  374. data_loader = load_breast_cancer()
  375. X = data_loader["data"]
  376. y = data_loader["target"]
  377. pd.DataFrame(X).to_hdf(data_path, key="X_train")
  378. pd.Series(y).to_hdf(data_path, key="y_train")
  379. cv = [(list(range(len(X)//3)), list(range(len(X)//3, len(X)))),
  380. (list(range(2*len(X)//3)), list(range(2*len(X)//3, len(X))))]
  381. pickle.dump(cv, open(cv_path, "wb"))
  382. hs = HyperoptPipelineSelector(cost_func=roc_auc_score,
  383. greater_is_better=True,
  384. trials_path=trials_path,
  385. additional_metrics=additional_metrics,
  386. strategy_name=strategy_name,
  387. stdout_log_level="WARNING")
  388. hs.attach_space(space=space)
  389. hs.attach_data_from_hdf5(data_hdf5_store_path=data_path,
  390. cv_pickle_path=cv_path)
  391. try:
  392. # TODO: this line causes a pytype to throw not-callable error
  393. # works fine with pytype on other class methods.
  394. save_method = MongodbHandler().insert_data_into_collection
  395. save_kwargs = {'collection_name': collection_name}
  396. # save_method = pd.DataFrame.to_excel()
  397. # save_kwargs = {'excel_writer': "TEST.xlsx"}
  398. hs.configer_summary_saving(save_method=save_method,
  399. kwargs=save_kwargs)
  400. logger.info("Configured summary saving in mongo")
  401. except Exception as e:
  402. logger.warning(("Could not configure summary saving in mongo. "
  403. "Exit with error: {}".format(e)))
  404. hs.run_trials(niter=10)
  405. logger.info("Best Trial: {}".format(hs.best_trial))
  406. logger.info("Total tuning time: {}".format(hs.total_tuning_time))
  407. for file in [trials_path, data_path, cv_path]:
  408. os.remove(file)
  409. logger.info("End test")