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