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.

basic_nn.py 20 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. from __future__ import annotations
  2. import logging
  3. import os
  4. from typing import Any, Callable, List, Optional, Tuple, Union
  5. import numpy
  6. import torch
  7. from torch.utils.data import DataLoader
  8. from ..utils.logger import print_log
  9. from .torch_dataset import ClassificationDataset, PredictionDataset
  10. class BasicNN:
  11. """
  12. Wrap NN models into the form of an sklearn estimator.
  13. Parameters
  14. ----------
  15. model : torch.nn.Module
  16. The PyTorch model to be trained or used for prediction.
  17. loss_fn : torch.nn.Module
  18. The loss function used for training.
  19. optimizer : torch.optim.Optimizer
  20. The optimizer used for training.
  21. scheduler : Callable[..., Any], optional
  22. The learning rate scheduler used for training, which will be called
  23. at the end of each run of the ``fit`` method. It should implement the
  24. ``step`` method, by default None.
  25. device : Union[torch.device, str]
  26. The device on which the model will be trained or used for prediction,
  27. by default torch.device("cpu").
  28. batch_size : int, optional
  29. The batch size used for training, by default 32.
  30. num_epochs : int, optional
  31. The number of epochs used for training, by default 1.
  32. stop_loss : float, optional
  33. The loss value at which to stop training, by default 0.0001.
  34. num_workers : int
  35. The number of workers used for loading data, by default 0.
  36. save_interval : int, optional
  37. The model will be saved every ``save_interval`` epochs during training, by default None.
  38. save_dir : str, optional
  39. The directory in which to save the model during training, by default None.
  40. train_transform : Callable[..., Any], optional
  41. A function/transform that takes an object and returns a transformed version used
  42. in the `fit` and `train_epoch` methods, by default None.
  43. test_transform : Callable[..., Any], optional
  44. A function/transform that takes an object and returns a transformed version in the
  45. `predict`, `predict_proba` and `score` methods, , by default None.
  46. collate_fn : Callable[[List[T]], Any], optional
  47. The function used to collate data, by default None.
  48. """
  49. def __init__(
  50. self,
  51. model: torch.nn.Module,
  52. loss_fn: torch.nn.Module,
  53. optimizer: torch.optim.Optimizer,
  54. scheduler: Optional[Callable[..., Any]] = None,
  55. device: Union[torch.device, str] = torch.device("cpu"),
  56. batch_size: int = 32,
  57. num_epochs: int = 1,
  58. stop_loss: Optional[float] = 0.0001,
  59. num_workers: int = 0,
  60. save_interval: Optional[int] = None,
  61. save_dir: Optional[str] = None,
  62. train_transform: Optional[Callable[..., Any]] = None,
  63. test_transform: Optional[Callable[..., Any]] = None,
  64. collate_fn: Optional[Callable[[List[Any]], Any]] = None,
  65. ) -> None:
  66. if not isinstance(model, torch.nn.Module):
  67. raise TypeError("model must be an instance of torch.nn.Module")
  68. if not isinstance(loss_fn, torch.nn.Module):
  69. raise TypeError("loss_fn must be an instance of torch.nn.Module")
  70. if not isinstance(optimizer, torch.optim.Optimizer):
  71. raise TypeError("optimizer must be an instance of torch.optim.Optimizer")
  72. if scheduler is not None and not hasattr(scheduler, "step"):
  73. raise NotImplementedError("scheduler should implement the ``step`` method")
  74. if not isinstance(device, torch.device):
  75. if not isinstance(device, str):
  76. raise TypeError(
  77. "device must be an instance of torch.device or a str indicates the target device"
  78. )
  79. else:
  80. device = torch.device(device)
  81. if not isinstance(batch_size, int):
  82. raise TypeError("batch_size must be an integer")
  83. if not isinstance(num_epochs, int):
  84. raise TypeError("num_epochs must be an integer")
  85. if stop_loss is not None and not isinstance(stop_loss, float):
  86. raise TypeError("stop_loss must be a float")
  87. if not isinstance(num_workers, int):
  88. raise TypeError("num_workers must be an integer")
  89. if save_interval is not None and not isinstance(save_interval, int):
  90. raise TypeError("save_interval must be an integer")
  91. if save_dir is not None and not isinstance(save_dir, str):
  92. raise TypeError("save_dir must be a string")
  93. if train_transform is not None and not callable(train_transform):
  94. raise TypeError("train_transform must be callable")
  95. if test_transform is not None and not callable(test_transform):
  96. raise TypeError("test_transform must be callable")
  97. if collate_fn is not None and not callable(collate_fn):
  98. raise TypeError("collate_fn must be callable")
  99. self.model = model.to(device)
  100. self.loss_fn = loss_fn
  101. self.optimizer = optimizer
  102. self.scheduler = scheduler
  103. self.device = device
  104. self.batch_size = batch_size
  105. self.num_epochs = num_epochs
  106. self.stop_loss = stop_loss
  107. self.num_workers = num_workers
  108. self.save_interval = save_interval
  109. self.save_dir = save_dir
  110. self.train_transform = train_transform
  111. self.test_transform = test_transform
  112. self.collate_fn = collate_fn
  113. if self.save_interval is not None and self.save_dir is None:
  114. raise ValueError("save_dir should not be None if save_interval is not None.")
  115. if self.train_transform is not None and self.test_transform is None:
  116. print_log(
  117. "Transform used in the training phase will be used in prediction.",
  118. logger="current",
  119. level=logging.WARNING,
  120. )
  121. self.test_transform = self.train_transform
  122. def _fit(self, data_loader: DataLoader) -> BasicNN:
  123. """
  124. Internal method to fit the model on data for ``self.num_epochs`` times,
  125. with early stopping.
  126. Parameters
  127. ----------
  128. data_loader : DataLoader
  129. Data loader providing training samples.
  130. Returns
  131. -------
  132. BasicNN
  133. The model itself after training.
  134. """
  135. if not isinstance(data_loader, DataLoader):
  136. raise TypeError(
  137. f"data_loader must be an instance of torch.utils.data.DataLoader, "
  138. f"but got {type(data_loader)}"
  139. )
  140. for epoch in range(self.num_epochs):
  141. loss_value = self.train_epoch(data_loader)
  142. if self.save_interval is not None and (epoch + 1) % self.save_interval == 0:
  143. self.save(epoch + 1)
  144. if self.stop_loss is not None and loss_value < self.stop_loss:
  145. break
  146. if self.scheduler is not None:
  147. self.scheduler.step()
  148. print_log(f"model loss: {loss_value:.5f}", logger="current")
  149. return self
  150. def fit(
  151. self, data_loader: DataLoader = None, X: List[Any] = None, y: List[int] = None
  152. ) -> BasicNN:
  153. """
  154. Train the model for self.num_epochs times or until the average loss on one epoch
  155. is less than self.stop_loss. It supports training with either a DataLoader
  156. object (data_loader) or a pair of input data (X) and target labels (y). If both
  157. data_loader and (X, y) are provided, the method will prioritize using the data_loader.
  158. Parameters
  159. ----------
  160. data_loader : DataLoader, optional
  161. The data loader used for training, by default None.
  162. X : List[Any], optional
  163. The input data, by default None.
  164. y : List[int], optional
  165. The target data, by default None.
  166. Returns
  167. -------
  168. BasicNN
  169. The model itself after training.
  170. """
  171. if data_loader is not None and X is not None:
  172. print_log(
  173. "data_loader will be used to train the model instead of X and y.",
  174. logger="current",
  175. level=logging.WARNING,
  176. )
  177. if data_loader is None:
  178. if X is None:
  179. raise ValueError("data_loader and X can not be None simultaneously.")
  180. else:
  181. data_loader = self._data_loader(X, y)
  182. return self._fit(data_loader)
  183. def train_epoch(self, data_loader: DataLoader) -> float:
  184. """
  185. Train the model with an instance of DataLoader (data_loader) for one epoch.
  186. Parameters
  187. ----------
  188. data_loader : DataLoader
  189. The data loader used for training.
  190. Returns
  191. -------
  192. float
  193. The average loss on one epoch.
  194. """
  195. model = self.model
  196. loss_fn = self.loss_fn
  197. optimizer = self.optimizer
  198. device = self.device
  199. model.train()
  200. total_loss, total_num = 0.0, 0
  201. for data, target in data_loader:
  202. data, target = data.to(device), target.to(device)
  203. out = model(data)
  204. loss = loss_fn(out, target)
  205. optimizer.zero_grad()
  206. loss.backward()
  207. optimizer.step()
  208. total_loss += loss.item() * data.size(0)
  209. total_num += data.size(0)
  210. return total_loss / total_num
  211. def _predict(self, data_loader: DataLoader) -> torch.Tensor:
  212. """
  213. Internal method to predict the outputs given a DataLoader.
  214. Parameters
  215. ----------
  216. data_loader : DataLoader
  217. The DataLoader providing input samples.
  218. Returns
  219. -------
  220. torch.Tensor
  221. Raw output from the model.
  222. """
  223. if not isinstance(data_loader, DataLoader):
  224. raise TypeError(
  225. f"data_loader must be an instance of torch.utils.data.DataLoader, "
  226. f"but got {type(data_loader)}"
  227. )
  228. model = self.model
  229. device = self.device
  230. model.eval()
  231. with torch.no_grad():
  232. results = []
  233. for data in data_loader:
  234. data = data.to(device)
  235. out = model(data)
  236. results.append(out)
  237. return torch.cat(results, axis=0)
  238. def predict(self, data_loader: DataLoader = None, X: List[Any] = None) -> numpy.ndarray:
  239. """
  240. Predict the class of the input data. This method supports prediction with either
  241. a DataLoader object (data_loader) or a list of input data (X). If both data_loader
  242. and X are provided, the method will predict the input data in data_loader
  243. instead of X.
  244. Parameters
  245. ----------
  246. data_loader : DataLoader, optional
  247. The data loader used for prediction, by default None.
  248. X : List[Any], optional
  249. The input data, by default None.
  250. Returns
  251. -------
  252. numpy.ndarray
  253. The predicted class of the input data.
  254. """
  255. if data_loader is not None and X is not None:
  256. print_log(
  257. "Predict the class of input data in data_loader instead of X.",
  258. logger="current",
  259. level=logging.WARNING,
  260. )
  261. if data_loader is None:
  262. dataset = PredictionDataset(X, self.test_transform)
  263. data_loader = DataLoader(
  264. dataset,
  265. batch_size=self.batch_size,
  266. num_workers=int(self.num_workers),
  267. collate_fn=self.collate_fn,
  268. )
  269. return self._predict(data_loader).argmax(axis=1).cpu().numpy()
  270. def predict_proba(self, data_loader: DataLoader = None, X: List[Any] = None) -> numpy.ndarray:
  271. """
  272. Predict the probability of each class for the input data. This method supports
  273. prediction with either a DataLoader object (data_loader) or a list of input data (X).
  274. If both data_loader and X are provided, the method will predict the input data in
  275. data_loader instead of X.
  276. Parameters
  277. ----------
  278. data_loader : DataLoader, optional
  279. The data loader used for prediction, by default None.
  280. X : List[Any], optional
  281. The input data, by default None.
  282. Returns
  283. -------
  284. numpy.ndarray
  285. The predicted probability of each class for the input data.
  286. """
  287. if data_loader is not None and X is not None:
  288. print_log(
  289. "Predict the class probability of input data in data_loader instead of X.",
  290. logger="current",
  291. level=logging.WARNING,
  292. )
  293. if data_loader is None:
  294. dataset = PredictionDataset(X, self.test_transform)
  295. data_loader = DataLoader(
  296. dataset,
  297. batch_size=self.batch_size,
  298. num_workers=int(self.num_workers),
  299. collate_fn=self.collate_fn,
  300. )
  301. return self._predict(data_loader).softmax(axis=1).cpu().numpy()
  302. def _score(self, data_loader: DataLoader) -> Tuple[float, float]:
  303. """
  304. Internal method to compute loss and accuracy for the data provided through a DataLoader.
  305. Parameters
  306. ----------
  307. data_loader : DataLoader
  308. Data loader to use for evaluation.
  309. Returns
  310. -------
  311. Tuple[float, float]
  312. mean_loss: float, The mean loss of the model on the provided data.
  313. accuracy: float, The accuracy of the model on the provided data.
  314. """
  315. if not isinstance(data_loader, DataLoader):
  316. raise TypeError(
  317. f"data_loader must be an instance of torch.utils.data.DataLoader, "
  318. f"but got {type(data_loader)}"
  319. )
  320. model = self.model
  321. loss_fn = self.loss_fn
  322. device = self.device
  323. model.eval()
  324. total_correct_num, total_num, total_loss = 0, 0, 0.0
  325. with torch.no_grad():
  326. for data, target in data_loader:
  327. data, target = data.to(device), target.to(device)
  328. out = model(data)
  329. if len(out.shape) > 1:
  330. correct_num = (target == out.argmax(axis=1)).sum().item()
  331. else:
  332. correct_num = (target == (out > 0.5)).sum().item()
  333. loss = loss_fn(out, target)
  334. total_loss += loss.item() * data.size(0)
  335. total_correct_num += correct_num
  336. total_num += data.size(0)
  337. mean_loss = total_loss / total_num
  338. accuracy = total_correct_num / total_num
  339. return mean_loss, accuracy
  340. def score(
  341. self, data_loader: DataLoader = None, X: List[Any] = None, y: List[int] = None
  342. ) -> float:
  343. """
  344. Validate the model. It supports validation with either a DataLoader object (data_loader)
  345. or a pair of input data (X) and ground truth labels (y). If both data_loader and
  346. (X, y) are provided, the method will prioritize using the data_loader.
  347. Parameters
  348. ----------
  349. data_loader : DataLoader, optional
  350. The data loader used for scoring, by default None.
  351. X : List[Any], optional
  352. The input data, by default None.
  353. y : List[int], optional
  354. The target data, by default None.
  355. Returns
  356. -------
  357. float
  358. The accuracy of the model.
  359. """
  360. print_log("Start machine learning model validation", logger="current")
  361. if data_loader is not None and X is not None:
  362. print_log(
  363. "data_loader will be used to validate the model instead of X and y.",
  364. logger="current",
  365. level=logging.WARNING,
  366. )
  367. if data_loader is None:
  368. if X is None or y is None:
  369. raise ValueError("data_loader and (X, y) can not be None simultaneously.")
  370. else:
  371. data_loader = self._data_loader(X, y)
  372. mean_loss, accuracy = self._score(data_loader)
  373. print_log(f"mean loss: {mean_loss:.3f}, accuray: {accuracy:.3f}", logger="current")
  374. return accuracy
  375. def _data_loader(self, X: List[Any], y: List[int] = None, shuffle: bool = True) -> DataLoader:
  376. """
  377. Generate a DataLoader for user-provided input data and target labels.
  378. Parameters
  379. ----------
  380. X : List[Any]
  381. Input samples.
  382. y : List[int], optional
  383. Target labels. If None, dummy labels are created, by default None.
  384. shuffle : bool, optional
  385. Whether to shuffle the data, by default True.
  386. Returns
  387. -------
  388. DataLoader
  389. A DataLoader providing batches of (X, y) pairs.
  390. """
  391. if X is None:
  392. raise ValueError("X should not be None.")
  393. if y is None:
  394. y = [0] * len(X)
  395. if not (len(y) == len(X)):
  396. raise ValueError("X and y should have equal length.")
  397. dataset = ClassificationDataset(X, y, transform=self.train_transform)
  398. data_loader = DataLoader(
  399. dataset,
  400. batch_size=self.batch_size,
  401. shuffle=shuffle,
  402. num_workers=int(self.num_workers),
  403. collate_fn=self.collate_fn,
  404. )
  405. return data_loader
  406. def save(self, epoch_id: int = 0, save_path: str = None) -> None:
  407. """
  408. Save the model and the optimizer. User can either provide a save_path or specify
  409. the epoch_id at which the model and optimizer is saved. if both save_path and
  410. epoch_id are provided, save_path will be used. If only epoch_id is specified,
  411. model and optimizer will be saved to the path f"model_checkpoint_epoch_{epoch_id}.pth"
  412. under ``self.save_dir``. save_path and epoch_id can not be None simultaneously.
  413. Parameters
  414. ----------
  415. epoch_id : int
  416. The epoch id.
  417. save_path : str, optional
  418. The path to save the model, by default None.
  419. """
  420. if self.save_dir is None and save_path is None:
  421. raise ValueError("'save_dir' and 'save_path' should not be None simultaneously.")
  422. if save_path is not None:
  423. if not os.path.exists(os.path.dirname(save_path)):
  424. os.makedirs(os.path.dirname(save_path))
  425. else:
  426. save_path = os.path.join(self.save_dir, f"model_checkpoint_epoch_{epoch_id}.pth")
  427. if not os.path.exists(self.save_dir):
  428. os.makedirs(self.save_dir)
  429. print_log(f"Checkpoints will be saved to {save_path}", logger="current")
  430. save_parma_dic = {
  431. "model": self.model.state_dict(),
  432. "optimizer": self.optimizer.state_dict(),
  433. }
  434. torch.save(save_parma_dic, save_path)
  435. def load(self, load_path: str) -> None:
  436. """
  437. Load the model and the optimizer.
  438. Parameters
  439. ----------
  440. load_path : str
  441. The directory to load the model, by default "".
  442. """
  443. if load_path is None:
  444. raise ValueError("Load path should not be None.")
  445. print_log(
  446. f"Loads checkpoint by local backend from path: {load_path}",
  447. logger="current",
  448. )
  449. param_dic = torch.load(load_path)
  450. self.model.load_state_dict(param_dic["model"])
  451. if "optimizer" in param_dic.keys():
  452. self.optimizer.load_state_dict(param_dic["optimizer"])

An efficient Python toolkit for Abductive Learning (ABL), a novel paradigm that integrates machine learning and logical reasoning in a unified framework.