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

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