HyperoptPipelineSelector.py 18 KB

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