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

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