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

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