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 33 kB

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