You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

node_classifier.py 29 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. """
  2. Auto Classfier for Node Classification
  3. """
  4. import time
  5. import json
  6. from copy import deepcopy
  7. import torch
  8. import numpy as np
  9. import yaml
  10. from .base import BaseClassifier
  11. from ..base import _parse_hp_space, _initialize_single_model
  12. from ...module.feature import FEATURE_DICT
  13. from ...module.model import MODEL_DICT, BaseModel
  14. from ...module.train import TRAINER_DICT, BaseNodeClassificationTrainer
  15. from ...module.train import get_feval
  16. from ..utils import Leaderboard, set_seed
  17. from ...datasets import utils
  18. from ...utils import get_logger
  19. LOGGER = get_logger("NodeClassifier")
  20. class AutoNodeClassifier(BaseClassifier):
  21. """
  22. Auto Multi-class Graph Node Classifier.
  23. Used to automatically solve the node classification problems.
  24. Parameters
  25. ----------
  26. feature_module: autogl.module.feature.BaseFeatureEngineer or str or None
  27. The (name of) auto feature engineer used to process the given dataset. Default ``deepgl``.
  28. Disable feature engineer by setting it to ``None``.
  29. graph_models: list of autogl.module.model.BaseModel or list of str
  30. The (name of) models to be optimized as backbone. Default ``['gat', 'gcn']``.
  31. hpo_module: autogl.module.hpo.BaseHPOptimizer or str or None
  32. The (name of) hpo module used to search for best hyper parameters. Default ``anneal``.
  33. Disable hpo by setting it to ``None``.
  34. ensemble_module: autogl.module.ensemble.BaseEnsembler or str or None
  35. The (name of) ensemble module used to ensemble the multi-models found. Default ``voting``.
  36. Disable ensemble by setting it to ``None``.
  37. max_evals: int (Optional)
  38. If given, will set the number eval times the hpo module will use.
  39. Only be effective when hpo_module is ``str``. Default ``None``.
  40. trainer_hp_space: list of dict (Optional)
  41. trainer hp space or list of trainer hp spaces configuration.
  42. If a single trainer hp is given, will specify the hp space of trainer for every model.
  43. If a list of trainer hp is given, will specify every model with corrsponding
  44. trainer hp space.
  45. Default ``None``.
  46. model_hp_spaces: list of list of dict (Optional)
  47. model hp space configuration.
  48. If given, will specify every hp space of every passed model. Default ``None``.
  49. size: int (Optional)
  50. The max models ensemble module will use. Default ``None``.
  51. device: torch.device or str
  52. The device where model will be running on. If set to ``auto``, will use gpu when available.
  53. You can also specify the device by directly giving ``gpu`` or ``cuda:0``, etc.
  54. Default ``auto``.
  55. """
  56. def __init__(
  57. self,
  58. feature_module=None,
  59. graph_models=("gat", "gcn"),
  60. hpo_module="anneal",
  61. ensemble_module="voting",
  62. max_evals=50,
  63. default_trainer=None,
  64. trainer_hp_space=None,
  65. model_hp_spaces=None,
  66. size=4,
  67. device="auto",
  68. ):
  69. super().__init__(
  70. feature_module=feature_module,
  71. graph_models=graph_models,
  72. hpo_module=hpo_module,
  73. ensemble_module=ensemble_module,
  74. max_evals=max_evals,
  75. default_trainer=default_trainer or "NodeClassificationFull",
  76. trainer_hp_space=trainer_hp_space,
  77. model_hp_spaces=model_hp_spaces,
  78. size=size,
  79. device=device,
  80. )
  81. # data to be kept when fit
  82. self.data = None
  83. def _init_graph_module(
  84. self, graph_models, num_classes, num_features, feval, device, loss
  85. ) -> "AutoNodeClassifier":
  86. # load graph network module
  87. self.graph_model_list = []
  88. if isinstance(graph_models, list):
  89. for model in graph_models:
  90. if isinstance(model, str):
  91. if model in MODEL_DICT:
  92. self.graph_model_list.append(
  93. MODEL_DICT[model](
  94. num_classes=num_classes,
  95. num_features=num_features,
  96. device=device,
  97. init=False,
  98. )
  99. )
  100. else:
  101. raise KeyError("cannot find model %s" % (model))
  102. elif isinstance(model, type) and issubclass(model, BaseModel):
  103. self.graph_model_list.append(
  104. model(
  105. num_classes=num_classes,
  106. num_features=num_features,
  107. device=device,
  108. init=False,
  109. )
  110. )
  111. elif isinstance(model, BaseModel):
  112. # setup the hp of num_classes and num_features
  113. model.set_num_classes(num_classes)
  114. model.set_num_features(num_features)
  115. self.graph_model_list.append(model.to(device))
  116. elif isinstance(model, BaseNodeClassificationTrainer):
  117. # receive a trainer list, put trainer to list
  118. assert (
  119. model.get_model() is not None
  120. ), "Passed trainer should contain a model"
  121. model.model.set_num_classes(num_classes)
  122. model.model.set_num_features(num_features)
  123. model.update_parameters(
  124. num_classes=num_classes,
  125. num_features=num_features,
  126. loss=loss,
  127. feval=feval,
  128. device=device,
  129. )
  130. self.graph_model_list.append(model)
  131. else:
  132. raise KeyError("cannot find graph network %s." % (model))
  133. else:
  134. raise ValueError(
  135. "need graph network to be (list of) str or a BaseModel class/instance, get",
  136. graph_models,
  137. "instead.",
  138. )
  139. # wrap all model_cls with specified trainer
  140. for i, model in enumerate(self.graph_model_list):
  141. # set model hp space
  142. if self._model_hp_spaces is not None:
  143. if self._model_hp_spaces[i] is not None:
  144. if isinstance(model, BaseNodeClassificationTrainer):
  145. model.model.hyper_parameter_space = self._model_hp_spaces[i]
  146. else:
  147. model.hyper_parameter_space = self._model_hp_spaces[i]
  148. # initialize trainer if needed
  149. if isinstance(model, BaseModel):
  150. name = (
  151. self._default_trainer
  152. if isinstance(self._default_trainer, str)
  153. else self._default_trainer[i]
  154. )
  155. model = TRAINER_DICT[name](
  156. model=model,
  157. num_features=num_features,
  158. num_classes=num_classes,
  159. loss=loss,
  160. feval=feval,
  161. device=device,
  162. init=False,
  163. )
  164. # set trainer hp space
  165. if self._trainer_hp_space is not None:
  166. if isinstance(self._trainer_hp_space[0], list):
  167. current_hp_for_trainer = self._trainer_hp_space[i]
  168. else:
  169. current_hp_for_trainer = self._trainer_hp_space
  170. model.hyper_parameter_space = current_hp_for_trainer
  171. self.graph_model_list[i] = model
  172. return self
  173. # pylint: disable=arguments-differ
  174. def fit(
  175. self,
  176. dataset,
  177. time_limit=-1,
  178. inplace=False,
  179. train_split=None,
  180. val_split=None,
  181. balanced=True,
  182. evaluation_method="infer",
  183. seed=None,
  184. ) -> "AutoNodeClassifier":
  185. """
  186. Fit current solver on given dataset.
  187. Parameters
  188. ----------
  189. dataset: torch_geometric.data.dataset.Dataset
  190. The dataset needed to fit on. This dataset must have only one graph.
  191. time_limit: int
  192. The time limit of the whole fit process (in seconds). If set below 0,
  193. will ignore time limit. Default ``-1``.
  194. inplace: bool
  195. Whether we process the given dataset in inplace manner. Default ``False``.
  196. Set it to True if you want to save memory by modifying the given dataset directly.
  197. train_split: float or int (Optional)
  198. The train ratio (in ``float``) or number (in ``int``) of dataset. If you want to
  199. use default train/val/test split in dataset, please set this to ``None``.
  200. Default ``None``.
  201. val_split: float or int (Optional)
  202. The validation ratio (in ``float``) or number (in ``int``) of dataset. If you want
  203. to use default train/val/test split in dataset, please set this to ``None``.
  204. Default ``None``.
  205. balanced: bool
  206. Wether to create the train/valid/test split in a balanced way.
  207. If set to ``True``, the train/valid will have the same number of different classes.
  208. Default ``True``.
  209. evaluation_method: (list of) str or autogl.module.train.evaluation
  210. A (list of) evaluation method for current solver. If ``infer``, will automatically
  211. determine. Default ``infer``.
  212. seed: int (Optional)
  213. The random seed. If set to ``None``, will run everything at random.
  214. Default ``None``.
  215. Returns
  216. -------
  217. self: autogl.solver.AutoNodeClassifier
  218. A reference of current solver.
  219. """
  220. set_seed(seed)
  221. if time_limit < 0:
  222. time_limit = 3600 * 24
  223. time_begin = time.time()
  224. # initialize leaderboard
  225. if evaluation_method == "infer":
  226. if hasattr(dataset, "metric"):
  227. evaluation_method = [dataset.metric]
  228. else:
  229. num_of_label = dataset.num_classes
  230. if num_of_label == 2:
  231. evaluation_method = ["auc"]
  232. else:
  233. evaluation_method = ["acc"]
  234. assert isinstance(evaluation_method, list)
  235. evaluator_list = get_feval(evaluation_method)
  236. self.leaderboard = Leaderboard(
  237. [e.get_eval_name() for e in evaluator_list],
  238. {e.get_eval_name(): e.is_higher_better() for e in evaluator_list},
  239. )
  240. # set up the dataset
  241. if train_split is not None and val_split is not None:
  242. size = dataset.data.x.shape[0]
  243. if balanced:
  244. train_split = (
  245. train_split if train_split > 1 else int(train_split * size)
  246. )
  247. val_split = val_split if val_split > 1 else int(val_split * size)
  248. utils.random_splits_mask_class(
  249. dataset,
  250. num_train_per_class=train_split // dataset.num_classes,
  251. num_val_per_class=val_split // dataset.num_classes,
  252. seed=seed,
  253. )
  254. else:
  255. train_split = train_split if train_split < 1 else train_split / size
  256. val_split = val_split if val_split < 1 else val_split / size
  257. utils.random_splits_mask(
  258. dataset, train_ratio=train_split, val_ratio=val_split
  259. )
  260. else:
  261. assert hasattr(dataset.data, "train_mask") and hasattr(
  262. dataset.data, "val_mask"
  263. ), (
  264. "The dataset has no default train/val split! Please manually pass "
  265. "train and val ratio."
  266. )
  267. LOGGER.info("Use the default train/val/test ratio in given dataset")
  268. # feature engineering
  269. if self.feature_module is not None:
  270. dataset = self.feature_module.fit_transform(dataset, inplace=inplace)
  271. self.dataset = dataset
  272. assert self.dataset[0].x is not None, (
  273. "Does not support fit on non node-feature dataset!"
  274. " Please add node features to dataset or specify feature engineers that generate"
  275. " node features."
  276. )
  277. # initialize graph networks
  278. self._init_graph_module(
  279. self.gml,
  280. num_features=self.dataset[0].x.shape[1],
  281. num_classes=dataset.num_classes,
  282. feval=evaluator_list,
  283. device=self.runtime_device,
  284. loss="cross_entropy" if not hasattr(dataset, "loss") else dataset.loss,
  285. )
  286. # train the models and tune hpo
  287. result_valid = []
  288. names = []
  289. for idx, model in enumerate(self.graph_model_list):
  290. time_for_each_model = (time_limit - time.time() + time_begin) / (
  291. len(self.graph_model_list) - idx
  292. )
  293. if self.hpo_module is None:
  294. model.initialize()
  295. model.train(self.dataset, True)
  296. optimized = model
  297. else:
  298. optimized, _ = self.hpo_module.optimize(
  299. trainer=model, dataset=self.dataset, time_limit=time_for_each_model
  300. )
  301. # to save memory, all the trainer derived will be mapped to cpu
  302. optimized.to(torch.device("cpu"))
  303. name = optimized.get_name_with_hp() + "_idx%d" % (idx)
  304. names.append(name)
  305. performance_on_valid, _ = optimized.get_valid_score(return_major=False)
  306. result_valid.append(optimized.get_valid_predict_proba().cpu().numpy())
  307. self.leaderboard.insert_model_performance(
  308. name,
  309. dict(
  310. zip(
  311. [e.get_eval_name() for e in evaluator_list],
  312. performance_on_valid,
  313. )
  314. ),
  315. )
  316. self.trained_models[name] = optimized
  317. # fit the ensemble model
  318. if self.ensemble_module is not None:
  319. performance = self.ensemble_module.fit(
  320. result_valid,
  321. self.dataset[0].y[self.dataset[0].val_mask].cpu().numpy(),
  322. names,
  323. evaluator_list,
  324. n_classes=dataset.num_classes,
  325. )
  326. self.leaderboard.insert_model_performance(
  327. "ensemble",
  328. dict(zip([e.get_eval_name() for e in evaluator_list], performance)),
  329. )
  330. return self
  331. def fit_predict(
  332. self,
  333. dataset,
  334. time_limit=-1,
  335. inplace=False,
  336. train_split=None,
  337. val_split=None,
  338. balanced=True,
  339. evaluation_method="infer",
  340. use_ensemble=True,
  341. use_best=True,
  342. name=None,
  343. ) -> np.ndarray:
  344. """
  345. Fit current solver on given dataset and return the predicted value.
  346. Parameters
  347. ----------
  348. dataset: torch_geometric.data.dataset.Dataset
  349. The dataset needed to fit on. This dataset must have only one graph.
  350. time_limit: int
  351. The time limit of the whole fit process (in seconds).
  352. If set below 0, will ignore time limit. Default ``-1``.
  353. inplace: bool
  354. Whether we process the given dataset in inplace manner. Default ``False``.
  355. Set it to True if you want to save memory by modifying the given dataset directly.
  356. train_split: float or int (Optional)
  357. The train ratio (in ``float``) or number (in ``int``) of dataset. If you want to
  358. use default train/val/test split in dataset, please set this to ``None``.
  359. Default ``None``.
  360. val_split: float or int (Optional)
  361. The validation ratio (in ``float``) or number (in ``int``) of dataset. If you want
  362. to use default train/val/test split in dataset, please set this to ``None``.
  363. Default ``None``.
  364. balanced: bool
  365. Wether to create the train/valid/test split in a balanced way.
  366. If set to ``True``, the train/valid will have the same number of different classes.
  367. Default ``False``.
  368. evaluation_method: (list of) str or autogl.module.train.evaluation
  369. A (list of) evaluation method for current solver. If ``infer``, will automatically
  370. determine. Default ``infer``.
  371. use_ensemble: bool
  372. Whether to use ensemble to do the predict. Default ``True``.
  373. use_best: bool
  374. Whether to use the best single model to do the predict. Will only be effective when
  375. ``use_ensemble`` is ``False``.
  376. Default ``True``.
  377. name: str or None
  378. The name of model used to predict. Will only be effective when ``use_ensemble`` and
  379. ``use_best`` both are ``False``.
  380. Default ``None``.
  381. Returns
  382. -------
  383. result: np.ndarray
  384. An array of shape ``(N,)``, where ``N`` is the number of test nodes. The prediction
  385. on given dataset.
  386. """
  387. self.fit(
  388. dataset=dataset,
  389. time_limit=time_limit,
  390. inplace=inplace,
  391. train_split=train_split,
  392. val_split=val_split,
  393. balanced=balanced,
  394. evaluation_method=evaluation_method,
  395. )
  396. return self.predict(
  397. dataset=dataset,
  398. inplaced=inplace,
  399. inplace=inplace,
  400. use_ensemble=use_ensemble,
  401. use_best=use_best,
  402. name=name,
  403. )
  404. def predict_proba(
  405. self,
  406. dataset=None,
  407. inplaced=False,
  408. inplace=False,
  409. use_ensemble=True,
  410. use_best=True,
  411. name=None,
  412. mask="test",
  413. ) -> np.ndarray:
  414. """
  415. Predict the node probability.
  416. Parameters
  417. ----------
  418. dataset: torch_geometric.data.dataset.Dataset or None
  419. The dataset needed to predict. If ``None``, will use the processed dataset passed
  420. to ``fit()`` instead. Default ``None``.
  421. inplaced: bool
  422. Whether the given dataset is processed. Only be effective when ``dataset``
  423. is not ``None``. If you pass the dataset to ``fit()`` with ``inplace=True``, and
  424. you pass the dataset again to this method, you should set this argument to ``True``.
  425. Otherwise ``False``. Default ``False``.
  426. inplace: bool
  427. Whether we process the given dataset in inplace manner. Default ``False``. Set it to
  428. True if you want to save memory by modifying the given dataset directly.
  429. use_ensemble: bool
  430. Whether to use ensemble to do the predict. Default ``True``.
  431. use_best: bool
  432. Whether to use the best single model to do the predict. Will only be effective when
  433. ``use_ensemble`` is ``False``. Default ``True``.
  434. name: str or None
  435. The name of model used to predict. Will only be effective when ``use_ensemble`` and
  436. ``use_best`` both are ``False``. Default ``None``.
  437. mask: str
  438. The data split to give prediction on. Default ``test``.
  439. Returns
  440. -------
  441. result: np.ndarray
  442. An array of shape ``(N,C,)``, where ``N`` is the number of test nodes and ``C`` is
  443. the number of classes. The prediction on given dataset.
  444. """
  445. if dataset is None:
  446. dataset = self.dataset
  447. assert dataset is not None, (
  448. "Please execute fit() first before" " predicting on remembered dataset"
  449. )
  450. elif not inplaced and self.feature_module is not None:
  451. dataset = self.feature_module.transform(dataset, inplace=inplace)
  452. if use_ensemble:
  453. LOGGER.info("Ensemble argument on, will try using ensemble model.")
  454. if not use_ensemble and use_best:
  455. LOGGER.info(
  456. "Ensemble argument off and best argument on, will try using best model."
  457. )
  458. if (use_ensemble and self.ensemble_module is not None) or (
  459. not use_best and name == "ensemble"
  460. ):
  461. # we need to get all the prediction of every model trained
  462. predict_result = []
  463. names = []
  464. for model_name in self.trained_models:
  465. predict_result.append(
  466. self._predict_proba_by_name(dataset, model_name, mask)
  467. )
  468. names.append(model_name)
  469. return self.ensemble_module.ensemble(predict_result, names)
  470. if use_ensemble and self.ensemble_module is None:
  471. LOGGER.warning(
  472. "Cannot use ensemble because no ensebmle module is given."
  473. "Will use best model instead."
  474. )
  475. if use_best or (use_ensemble and self.ensemble_module is None):
  476. # just return the best model we have found
  477. name = self.leaderboard.get_best_model()
  478. return self._predict_proba_by_name(dataset, name, mask)
  479. if name is not None:
  480. # return model performance by name
  481. return self._predict_proba_by_name(dataset, name, mask)
  482. LOGGER.error(
  483. "No model name is given while ensemble and best arguments are off."
  484. )
  485. raise ValueError(
  486. "You need to specify a model name if you do not want use ensemble and best model."
  487. )
  488. def _predict_proba_by_name(self, dataset, name, mask="test"):
  489. self.trained_models[name].to(self.runtime_device)
  490. predicted = (
  491. self.trained_models[name].predict_proba(dataset, mask=mask).cpu().numpy()
  492. )
  493. self.trained_models[name].to(torch.device("cpu"))
  494. return predicted
  495. def predict(
  496. self,
  497. dataset=None,
  498. inplaced=False,
  499. inplace=False,
  500. use_ensemble=True,
  501. use_best=True,
  502. name=None,
  503. mask="test",
  504. ) -> np.ndarray:
  505. """
  506. Predict the node class number.
  507. Parameters
  508. ----------
  509. dataset: torch_geometric.data.dataset.Dataset or None
  510. The dataset needed to predict. If ``None``, will use the processed dataset passed
  511. to ``fit()`` instead. Default ``None``.
  512. inplaced: bool
  513. Whether the given dataset is processed. Only be effective when ``dataset``
  514. is not ``None``. If you pass the dataset to ``fit()`` with ``inplace=True``,
  515. and you pass the dataset again to this method, you should set this argument
  516. to ``True``. Otherwise ``False``. Default ``False``.
  517. inplace: bool
  518. Whether we process the given dataset in inplace manner. Default ``False``.
  519. Set it to True if you want to save memory by modifying the given dataset directly.
  520. use_ensemble: bool
  521. Whether to use ensemble to do the predict. Default ``True``.
  522. use_best: bool
  523. Whether to use the best single model to do the predict. Will only be effective
  524. when ``use_ensemble`` is ``False``. Default ``True``.
  525. name: str or None
  526. The name of model used to predict. Will only be effective when ``use_ensemble``
  527. and ``use_best`` both are ``False``. Default ``None``.
  528. mask: str
  529. The data split to give prediction on. Default ``test``.
  530. Returns
  531. -------
  532. result: np.ndarray
  533. An array of shape ``(N,)``, where ``N`` is the number of test nodes.
  534. The prediction on given dataset.
  535. """
  536. proba = self.predict_proba(
  537. dataset, inplaced, inplace, use_ensemble, use_best, name, mask
  538. )
  539. return np.argmax(proba, axis=1)
  540. @classmethod
  541. def from_config(cls, path_or_dict, filetype="auto") -> "AutoNodeClassifier":
  542. """
  543. Load solver from config file.
  544. You can use this function to directly load a solver from predefined config dict
  545. or config file path. Currently, only support file type of ``json`` or ``yaml``,
  546. if you pass a path.
  547. Parameters
  548. ----------
  549. path_or_dict: str or dict
  550. The path to the config file or the config dictionary object
  551. filetype: str
  552. The filetype the given file if the path is specified. Currently only support
  553. ``json`` or ``yaml``. You can set to ``auto`` to automatically detect the file
  554. type (from file name). Default ``auto``.
  555. Returns
  556. -------
  557. solver: autogl.solver.AutoGraphClassifier
  558. The solver that is created from given file or dictionary.
  559. """
  560. assert filetype in ["auto", "yaml", "json"], (
  561. "currently only support yaml file or json file type, but get type "
  562. + filetype
  563. )
  564. if isinstance(path_or_dict, str):
  565. if filetype == "auto":
  566. if path_or_dict.endswith(".yaml") or path_or_dict.endswith(".yml"):
  567. filetype = "yaml"
  568. elif path_or_dict.endswith(".json"):
  569. filetype = "json"
  570. else:
  571. LOGGER.error(
  572. "cannot parse the type of the given file name, "
  573. "please manually set the file type"
  574. )
  575. raise ValueError(
  576. "cannot parse the type of the given file name, "
  577. "please manually set the file type"
  578. )
  579. if filetype == "yaml":
  580. path_or_dict = yaml.load(
  581. open(path_or_dict, "r").read(), Loader=yaml.FullLoader
  582. )
  583. else:
  584. path_or_dict = json.load(open(path_or_dict, "r"))
  585. path_or_dict = deepcopy(path_or_dict)
  586. solver = cls(None, [], None, None)
  587. fe_list = path_or_dict.pop("feature", None)
  588. if fe_list is not None:
  589. fe_list_ele = []
  590. for feature_engineer in fe_list:
  591. name = feature_engineer.pop("name")
  592. if name is not None:
  593. fe_list_ele.append(FEATURE_DICT[name](**feature_engineer))
  594. if fe_list_ele != []:
  595. solver.set_feature_module(fe_list_ele)
  596. models = path_or_dict.pop("models", [{"name": "gcn"}, {"name": "gat"}])
  597. model_hp_space = [
  598. _parse_hp_space(model.pop("hp_space", None)) for model in models
  599. ]
  600. model_list = [
  601. _initialize_single_model(model.pop("name"), model) for model in models
  602. ]
  603. trainer = path_or_dict.pop("trainer", None)
  604. default_trainer = "NodeClassificationFull"
  605. trainer_space = None
  606. if isinstance(trainer, dict):
  607. # global default
  608. default_trainer = trainer.pop("name", "NodeClassificationFull")
  609. trainer_space = _parse_hp_space(trainer.pop("hp_space", None))
  610. default_kwargs = {"num_features": None, "num_classes": None}
  611. default_kwargs.update(trainer)
  612. default_kwargs["init"] = False
  613. for i in range(len(model_list)):
  614. model = model_list[i]
  615. trainer_wrap = TRAINER_DICT[default_trainer](
  616. model=model, **default_kwargs
  617. )
  618. model_list[i] = trainer_wrap
  619. elif isinstance(trainer, list):
  620. # sequential trainer definition
  621. assert len(trainer) == len(
  622. model_list
  623. ), "The number of trainer and model does not match"
  624. trainer_space = []
  625. for i in range(len(model_list)):
  626. train, model = trainer[i], model_list[i]
  627. default_trainer = train.pop("name", "NodeClassificationFull")
  628. trainer_space.append(_parse_hp_space(train.pop("hp_space", None)))
  629. default_kwargs = {"num_features": None, "num_classes": None}
  630. default_kwargs.update(train)
  631. default_kwargs["init"] = False
  632. trainer_wrap = TRAINER_DICT[default_trainer](
  633. model=model, **default_kwargs
  634. )
  635. model_list[i] = trainer_wrap
  636. solver.set_graph_models(
  637. model_list, default_trainer, trainer_space, model_hp_space
  638. )
  639. hpo_dict = path_or_dict.pop("hpo", {"name": "anneal"})
  640. if hpo_dict is not None:
  641. name = hpo_dict.pop("name")
  642. solver.set_hpo_module(name, **hpo_dict)
  643. ensemble_dict = path_or_dict.pop("ensemble", {"name": "voting"})
  644. if ensemble_dict is not None:
  645. name = ensemble_dict.pop("name")
  646. solver.set_ensemble_module(name, **ensemble_dict)
  647. return solver