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.

PyodIsolationForest.py 11 kB

first commit Former-commit-id: 08bc23ba02cffbce3cf63962390a65459a132e48 [formerly 0795edd4834b9b7dc66db8d10d4cbaf42bbf82cb] [formerly b5010b42541add7e2ea2578bf2da537efc457757 [formerly a7ca09c2c34c4fc8b3d8e01fcfa08eeeb2cae99d]] [formerly 615058473a2177ca5b89e9edbb797f4c2a59c7e5 [formerly 743d8dfc6843c4c205051a8ab309fbb2116c895e] [formerly bb0ea98b1e14154ef464e2f7a16738705894e54b [formerly 960a69da74b81ef8093820e003f2d6c59a34974c]]] [formerly 2fa3be52c1b44665bc81a7cc7d4cea4bbf0d91d5 [formerly 2054589f0898627e0a17132fd9d4cc78efc91867] [formerly 3b53730e8a895e803dfdd6ca72bc05e17a4164c1 [formerly 8a2fa8ab7baf6686d21af1f322df46fd58c60e69]] [formerly 87d1e3a07a19d03c7d7c94d93ab4fa9f58dada7c [formerly f331916385a5afac1234854ee8d7f160f34b668f] [formerly 69fb3c78a483343f5071da4f7e2891b83a49dd18 [formerly 386086f05aa9487f65bce2ee54438acbdce57650]]]] Former-commit-id: a00aed8c934a6460c4d9ac902b9a74a3d6864697 [formerly 26fdeca29c2f07916d837883983ca2982056c78e] [formerly 0e3170d41a2f99ecf5c918183d361d4399d793bf [formerly 3c12ad4c88ac5192e0f5606ac0d88dd5bf8602dc]] [formerly d5894f84f2fd2e77a6913efdc5ae388cf1be0495 [formerly ad3e7bc670ff92c992730d29c9d3aa1598d844e8] [formerly 69fb3c78a483343f5071da4f7e2891b83a49dd18]] Former-commit-id: 3c19c9fae64f6106415fbc948a4dc613b9ee12f8 [formerly 467ddc0549c74bb007e8f01773bb6dc9103b417d] [formerly 5fa518345d958e2760e443b366883295de6d991c [formerly 3530e130b9fdb7280f638dbc2e785d2165ba82aa]] Former-commit-id: 9f5d473d42a435ec0d60149939d09be1acc25d92 [formerly be0b25c4ec2cde052a041baf0e11f774a158105d] Former-commit-id: 9eca71cb73ba9edccd70ac06a3b636b8d4093b04
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. from typing import Any, Callable, List, Dict, Union, Optional, Sequence, Tuple
  2. from numpy import ndarray
  3. from collections import OrderedDict
  4. from scipy import sparse
  5. import os
  6. import sklearn
  7. import numpy
  8. import typing
  9. # Custom import commands if any
  10. import warnings
  11. import numpy as np
  12. from sklearn.utils import check_array
  13. from sklearn.exceptions import NotFittedError
  14. # from numba import njit
  15. from pyod.utils.utility import argmaxn
  16. from d3m.container.numpy import ndarray as d3m_ndarray
  17. from d3m.container import DataFrame as d3m_dataframe
  18. from d3m.metadata import hyperparams, params, base as metadata_base
  19. from d3m import utils
  20. from d3m.base import utils as base_utils
  21. from d3m.exceptions import PrimitiveNotFittedError
  22. from d3m.primitive_interfaces.base import CallResult, DockerContainer
  23. # from d3m.primitive_interfaces.supervised_learning import SupervisedLearnerPrimitiveBase
  24. from d3m.primitive_interfaces.unsupervised_learning import UnsupervisedLearnerPrimitiveBase
  25. from d3m.primitive_interfaces.transformer import TransformerPrimitiveBase
  26. from d3m.primitive_interfaces.base import ProbabilisticCompositionalityMixin, ContinueFitMixin
  27. from d3m import exceptions
  28. import pandas
  29. from d3m import container, utils as d3m_utils
  30. from detection_algorithm.UODBasePrimitive import Params_ODBase, Hyperparams_ODBase, UnsupervisedOutlierDetectorBase
  31. from pyod.models.iforest import IForest
  32. from typing import Union
  33. import uuid
  34. Inputs = d3m_dataframe
  35. Outputs = d3m_dataframe
  36. class Params(Params_ODBase):
  37. ######## Add more Attributes #######
  38. pass
  39. class Hyperparams(Hyperparams_ODBase):
  40. ######## Add more Hyperparamters #######
  41. n_estimators = hyperparams.Hyperparameter[int](
  42. default=100,
  43. description='The number of base estimators in the ensemble.',
  44. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  45. )
  46. max_samples = hyperparams.Enumeration[str](
  47. values=['auto', 'int', 'float'],
  48. default='auto', # 'box-cox', #
  49. description='The number of samples to draw from X to train each base estimator.',
  50. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  51. )
  52. max_features = hyperparams.Hyperparameter[float](
  53. default=1.,
  54. description='The number of features to draw from X to train each base estimator.',
  55. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  56. )
  57. bootstrap = hyperparams.UniformBool(
  58. default=False,
  59. description='If True, individual trees are fit on random subsets of the training data sampled with replacement. If False, sampling without replacement is performed.',
  60. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  61. )
  62. behaviour = hyperparams.Enumeration[str](
  63. values=['old', 'new'],
  64. default='new',
  65. description='Refer to https://github.com/yzhao062/pyod/blob/master/pyod/models/iforest.py.',
  66. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  67. )
  68. random_state = hyperparams.Union[Union[int, None]](
  69. configuration=OrderedDict(
  70. init=hyperparams.Hyperparameter[int](
  71. default=0,
  72. ),
  73. ninit=hyperparams.Hyperparameter[None](
  74. default=None,
  75. ),
  76. ),
  77. default='ninit',
  78. description='the seed used by the random number generator.',
  79. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
  80. )
  81. verbose = hyperparams.Hyperparameter[int](
  82. default=0,
  83. description='Controls the verbosity of the tree building process.',
  84. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  85. )
  86. pass
  87. class IsolationForest(UnsupervisedOutlierDetectorBase[Inputs, Outputs, Params, Hyperparams]):
  88. """
  89. Wrapper of Pyod Isolation Forest with more functionalities.
  90. The IsolationForest 'isolates' observations by randomly selecting a
  91. feature and then randomly selecting a split value between the maximum and
  92. minimum values of the selected feature.
  93. See :cite:`liu2008isolation,liu2012isolation` for details.
  94. Since recursive partitioning can be represented by a tree structure, the
  95. number of splittings required to isolate a sample is equivalent to the path
  96. length from the root node to the terminating node.
  97. This path length, averaged over a forest of such random trees, is a
  98. measure of normality and our decision function.
  99. Random partitioning produces noticeably shorter paths for anomalies.
  100. Hence, when a forest of random trees collectively produce shorter path
  101. lengths for particular samples, they are highly likely to be anomalies.
  102. Parameters
  103. ----------
  104. n_estimators : int, optional (default=100)
  105. The number of base estimators in the ensemble.
  106. max_samples : int or float, optional (default="auto")
  107. The number of samples to draw from X to train each base estimator.
  108. - If int, then draw `max_samples` samples.
  109. - If float, then draw `max_samples * X.shape[0]` samples.
  110. - If "auto", then `max_samples=min(256, n_samples)`.
  111. If max_samples is larger than the number of samples provided,
  112. all samples will be used for all trees (no sampling).
  113. contamination : float in (0., 0.5), optional (default=0.1)
  114. The amount of contamination of the data set, i.e. the proportion
  115. of outliers in the data set. Used when fitting to define the threshold
  116. on the decision function.
  117. max_features : int or float, optional (default=1.0)
  118. The number of features to draw from X to train each base estimator.
  119. - If int, then draw `max_features` features.
  120. - If float, then draw `max_features * X.shape[1]` features.
  121. bootstrap : bool, optional (default=False)
  122. If True, individual trees are fit on random subsets of the training
  123. data sampled with replacement. If False, sampling without replacement
  124. is performed.
  125. behaviour : str, default='old'
  126. Behaviour of the ``decision_function`` which can be either 'old' or
  127. 'new'. Passing ``behaviour='new'`` makes the ``decision_function``
  128. change to match other anomaly detection algorithm API which will be
  129. the default behaviour in the future. As explained in details in the
  130. ``offset_`` attribute documentation, the ``decision_function`` becomes
  131. dependent on the contamination parameter, in such a way that 0 becomes
  132. its natural threshold to detect outliers.
  133. random_state : int, RandomState instance or None, optional (default=None)
  134. If int, random_state is the seed used by the random number generator;
  135. If RandomState instance, random_state is the random number generator;
  136. If None, the random number generator is the RandomState instance used
  137. by `np.random`.
  138. verbose : int, optional (default=0)
  139. Controls the verbosity of the tree building process.
  140. Attributes
  141. ----------
  142. decision_scores_ : numpy array of shape (n_samples,)
  143. The outlier scores of the training data.
  144. The higher, the more abnormal. Outliers tend to have higher
  145. scores. This value is available once the detector is
  146. fitted.
  147. threshold_ : float
  148. The threshold is based on ``contamination``. It is the
  149. ``n_samples * contamination`` most abnormal samples in
  150. ``decision_scores_``. The threshold is calculated for generating
  151. binary outlier labels.
  152. labels_ : int, either 0 or 1
  153. The binary labels of the training data. 0 stands for inliers
  154. and 1 for outliers/anomalies. It is generated by applying
  155. ``threshold_`` on ``decision_scores_``.
  156. """
  157. metadata = metadata_base.PrimitiveMetadata({
  158. "name": "TODS.anomaly_detection_primitives.IsolationForest",
  159. "python_path": "d3m.primitives.tods.detection_algorithm.pyod_iforest",
  160. "source": {'name': "DATALAB @Taxes A&M University", 'contact': 'mailto:khlai037@tamu.edu',
  161. 'uris': ['https://gitlab.com/lhenry15/tods.git']},
  162. "algorithm_types": [metadata_base.PrimitiveAlgorithmType.ISOLATION_FOREST, ],
  163. "primitive_family": metadata_base.PrimitiveFamily.ANOMALY_DETECTION,
  164. "version": "0.0.1",
  165. "hyperparams_to_tune": ['n_estimators', 'contamination'],
  166. "id": str(uuid.uuid3(uuid.NAMESPACE_DNS, 'IsolationForest'))
  167. })
  168. def __init__(self, *,
  169. hyperparams: Hyperparams, #
  170. random_seed: int = 0,
  171. docker_containers: Dict[str, DockerContainer] = None) -> None:
  172. super().__init__(hyperparams=hyperparams, random_seed=random_seed, docker_containers=docker_containers)
  173. self._clf = IForest(contamination=hyperparams['contamination'],
  174. n_estimators=hyperparams['n_estimators'],
  175. max_samples=hyperparams['max_samples'],
  176. max_features=hyperparams['max_features'],
  177. bootstrap=hyperparams['bootstrap'],
  178. behaviour=hyperparams['behaviour'],
  179. random_state=hyperparams['random_state'],
  180. verbose=hyperparams['verbose'],
  181. )
  182. return
  183. def set_training_data(self, *, inputs: Inputs) -> None:
  184. """
  185. Set training data for outlier detection.
  186. Args:
  187. inputs: Container DataFrame
  188. Returns:
  189. None
  190. """
  191. super().set_training_data(inputs=inputs)
  192. def fit(self, *, timeout: float = None, iterations: int = None) -> CallResult[None]:
  193. """
  194. Fit model with training data.
  195. Args:
  196. *: Container DataFrame. Time series data up to fit.
  197. Returns:
  198. None
  199. """
  200. return super().fit()
  201. def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> CallResult[Outputs]:
  202. """
  203. Process the testing data.
  204. Args:
  205. inputs: Container DataFrame. Time series data up to outlier detection.
  206. Returns:
  207. Container DataFrame
  208. 1 marks Outliers, 0 marks normal.
  209. """
  210. return super().produce(inputs=inputs, timeout=timeout, iterations=iterations)
  211. def get_params(self) -> Params:
  212. """
  213. Return parameters.
  214. Args:
  215. None
  216. Returns:
  217. class Params
  218. """
  219. return super().get_params()
  220. def set_params(self, *, params: Params) -> None:
  221. """
  222. Set parameters for outlier detection.
  223. Args:
  224. params: class Params
  225. Returns:
  226. None
  227. """
  228. super().set_params(params=params)

全栈的自动化机器学习系统,主要针对多变量时间序列数据的异常检测。TODS提供了详尽的用于构建基于机器学习的异常检测系统的模块,它们包括:数据处理(data processing),时间序列处理( time series processing),特征分析(feature analysis),检测算法(detection algorithms),和强化模块( reinforcement module)。这些模块所提供的功能包括常见的数据预处理、时间序列数据的平滑或变换,从时域或频域中抽取特征、多种多样的检测算