HyperoptPipelineSelector.py 18 KB

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