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.

PyodCBLOF.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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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.cblof import CBLOF
  32. import uuid
  33. # from typing import Union
  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_clusters = hyperparams.Hyperparameter[int](
  42. default=8,
  43. description='The number of clusters to form as well as the number of centroids to generate.',
  44. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  45. )
  46. # clustering_estimator = hyperparams.Choice(
  47. # choices={
  48. # 'auto': hyperparams.Hyperparams.define(
  49. # configuration=OrderedDict({})
  50. # ),
  51. # 'full': hyperparams.Hyperparams.define(
  52. # configuration=OrderedDict({})
  53. # ),
  54. # },
  55. # default='auto',
  56. # description='The base clustering algorithm for performing data clustering. A valid clustering algorithm should be passed in. The estimator should have standard sklearn APIs, fit() and predict(). The estimator should have attributes ``labels_`` and ``cluster_centers_``.',
  57. # semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  58. # )
  59. alpha = hyperparams.Uniform(
  60. lower=0.5,
  61. upper=1.,
  62. default=0.9,
  63. description='Coefficient for deciding small and large clusters. The ratio of the number of samples in large clusters to the number of samples in small clusters.',
  64. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  65. )
  66. beta = hyperparams.Hyperparameter[int](
  67. default=5,
  68. description='Coefficient for deciding small and large clusters.',
  69. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  70. )
  71. use_weights = hyperparams.UniformBool(
  72. default=False,
  73. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter'],
  74. description="If set to True, the size of clusters are used as weights in outlier score calculation."
  75. )
  76. check_estimator = hyperparams.UniformBool(
  77. default=False,
  78. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter'],
  79. description="If set to True, check whether the base estimator is consistent with sklearn standard."
  80. )
  81. random_state = hyperparams.Union[Union[int, None]](
  82. configuration=OrderedDict(
  83. init=hyperparams.Hyperparameter[int](
  84. default=0,
  85. ),
  86. ninit=hyperparams.Hyperparameter[None](
  87. default=None,
  88. ),
  89. ),
  90. default='ninit',
  91. description='the seed used by the random number generator.',
  92. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
  93. )
  94. pass
  95. class CBLOFPrimitive(UnsupervisedOutlierDetectorBase[Inputs, Outputs, Params, Hyperparams]):
  96. """
  97. The CBLOF operator calculates the outlier score based on cluster-based
  98. local outlier factor.
  99. CBLOF takes as an input the data set and the cluster model that was
  100. generated by a clustering algorithm. It classifies the clusters into small
  101. clusters and large clusters using the parameters alpha and beta.
  102. The anomaly score is then calculated based on the size of the cluster the
  103. point belongs to as well as the distance to the nearest large cluster.
  104. Use weighting for outlier factor based on the sizes of the clusters as
  105. proposed in the original publication. Since this might lead to unexpected
  106. behavior (outliers close to small clusters are not found), it is disabled
  107. by default.Outliers scores are solely computed based on their distance to
  108. the closest large cluster center.
  109. By default, kMeans is used for clustering algorithm instead of
  110. Squeezer algorithm mentioned in the original paper for multiple reasons.
  111. See :cite:`he2003discovering` for details.
  112. Parameters
  113. ----------
  114. n_clusters : int, optional (default=8)
  115. The number of clusters to form as well as the number of
  116. centroids to generate.
  117. contamination : float in (0., 0.5), optional (default=0.1)
  118. The amount of contamination of the data set,
  119. i.e. the proportion of outliers in the data set. Used when fitting to
  120. define the threshold on the decision function.
  121. clustering_estimator : Estimator, optional (default=None)
  122. The base clustering algorithm for performing data clustering.
  123. A valid clustering algorithm should be passed in. The estimator should
  124. have standard sklearn APIs, fit() and predict(). The estimator should
  125. have attributes ``labels_`` and ``cluster_centers_``.
  126. If ``cluster_centers_`` is not in the attributes once the model is fit,
  127. it is calculated as the mean of the samples in a cluster.
  128. If not set, CBLOF uses KMeans for scalability. See
  129. https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html
  130. alpha : float in (0.5, 1), optional (default=0.9)
  131. Coefficient for deciding small and large clusters. The ratio
  132. of the number of samples in large clusters to the number of samples in
  133. small clusters.
  134. beta : int or float in (1,), optional (default=5).
  135. Coefficient for deciding small and large clusters. For a list
  136. sorted clusters by size `|C1|, \|C2|, ..., |Cn|, beta = |Ck|/|Ck-1|`
  137. use_weights : bool, optional (default=False)
  138. If set to True, the size of clusters are used as weights in
  139. outlier score calculation.
  140. check_estimator : bool, optional (default=False)
  141. If set to True, check whether the base estimator is consistent with
  142. sklearn standard.
  143. .. warning::
  144. check_estimator may throw errors with scikit-learn 0.20 above.
  145. random_state : int, RandomState or None, optional (default=None)
  146. If int, random_state is the seed used by the random
  147. number generator; If RandomState instance, random_state is the random
  148. number generator; If None, the random number generator is the
  149. RandomState instance used by `np.random`.
  150. Attributes
  151. ----------
  152. decision_scores_ : numpy array of shape (n_samples,)
  153. The outlier scores of the training data.
  154. The higher, the more abnormal. Outliers tend to have higher
  155. scores. This value is available once the detector is
  156. fitted.
  157. threshold_ : float
  158. The threshold is based on ``contamination``. It is the
  159. ``n_samples * contamination`` most abnormal samples in
  160. ``decision_scores_``. The threshold is calculated for generating
  161. binary outlier labels.
  162. labels_ : int, either 0 or 1
  163. The binary labels of the training data. 0 stands for inliers
  164. and 1 for outliers/anomalies. It is generated by applying
  165. ``threshold_`` on ``decision_scores_``.
  166. """
  167. metadata = metadata_base.PrimitiveMetadata({
  168. "name": "TODS.anomaly_detection_primitives.CBLOFPrimitive",
  169. "python_path": "d3m.primitives.tods.detection_algorithm.pyod_cblof",
  170. "source": {'name': "DATALAB @Taxes A&M University", 'contact': 'mailto:khlai037@tamu.edu',
  171. 'uris': ['https://gitlab.com/lhenry15/tods.git']},
  172. "algorithm_types": [metadata_base.PrimitiveAlgorithmType.LOCAL_OUTLIER_FACTOR, ],
  173. "primitive_family": metadata_base.PrimitiveFamily.ANOMALY_DETECTION,
  174. "version": "0.0.1",
  175. "hyperparams_to_tune": ['contamination'],
  176. "id": str(uuid.uuid3(uuid.NAMESPACE_DNS, 'CBLOFPrimitive')),
  177. })
  178. def __init__(self, *,
  179. hyperparams: Hyperparams, #
  180. random_seed: int = 0,
  181. docker_containers: Dict[str, DockerContainer] = None) -> None:
  182. super().__init__(hyperparams=hyperparams, random_seed=random_seed, docker_containers=docker_containers)
  183. self._clf = CBLOF(contamination=hyperparams['contamination'],
  184. n_clusters=hyperparams['n_clusters'],
  185. alpha=hyperparams['alpha'],
  186. beta=hyperparams['beta'],
  187. use_weights=hyperparams['use_weights'],
  188. check_estimator=hyperparams['check_estimator'],
  189. random_state=hyperparams['random_state'],
  190. )
  191. return
  192. def set_training_data(self, *, inputs: Inputs) -> None:
  193. """
  194. Set training data for outlier detection.
  195. Args:
  196. inputs: Container DataFrame
  197. Returns:
  198. None
  199. """
  200. super().set_training_data(inputs=inputs)
  201. def fit(self, *, timeout: float = None, iterations: int = None) -> CallResult[None]:
  202. """
  203. Fit model with training data.
  204. Args:
  205. *: Container DataFrame. Time series data up to fit.
  206. Returns:
  207. None
  208. """
  209. return super().fit()
  210. def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> CallResult[Outputs]:
  211. """
  212. Process the testing data.
  213. Args:
  214. inputs: Container DataFrame. Time series data up to outlier detection.
  215. Returns:
  216. Container DataFrame
  217. 1 marks Outliers, 0 marks normal.
  218. """
  219. return super().produce(inputs=inputs, timeout=timeout, iterations=iterations)
  220. def get_params(self) -> Params:
  221. """
  222. Return parameters.
  223. Args:
  224. None
  225. Returns:
  226. class Params
  227. """
  228. return super().get_params()
  229. def set_params(self, *, params: Params) -> None:
  230. """
  231. Set parameters for outlier detection.
  232. Args:
  233. params: class Params
  234. Returns:
  235. None
  236. """
  237. super().set_params(params=params)

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