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.

PyodSOD.py 6.7 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. import uuid
  30. from d3m import container, utils as d3m_utils
  31. from detection_algorithm.UODBasePrimitive import Params_ODBase, Hyperparams_ODBase, UnsupervisedOutlierDetectorBase
  32. from pyod.models.sod import SOD
  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_neighbors = hyperparams.Hyperparameter[int](
  42. default=20,
  43. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter'],
  44. description="Number of neighbors to use by default for k neighbors queries.",
  45. )
  46. ref_set = hyperparams.Hyperparameter[int](
  47. default=10,
  48. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter'],
  49. description="specifies the number of shared nearest neighbors to create the reference set. Note that ref_set must be smaller than n_neighbors.",
  50. )
  51. alpha = hyperparams.Hyperparameter[float](
  52. default=0.8,
  53. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter'],
  54. description="specifies the lower limit for selecting subspace. 0.8 is set as default as suggested in the original paper.",
  55. )
  56. class SODPrimitive(UnsupervisedOutlierDetectorBase[Inputs, Outputs, Params, Hyperparams]):
  57. """
  58. Subspace outlier detection (SOD) schema aims to detect outlier in
  59. varying subspaces of a high dimensional feature space. For each data
  60. object, SOD explores the axis-parallel subspace spanned by the data
  61. object's neighbors and determines how much the object deviates from the
  62. neighbors in this subspace.
  63. See :cite:`kriegel2009outlier` for details.
  64. Parameters
  65. ----------
  66. n_neighbors : int, optional (default=20)
  67. Number of neighbors to use by default for k neighbors queries.
  68. ref_set: int, optional (default=10)
  69. specifies the number of shared nearest neighbors to create the
  70. reference set. Note that ref_set must be smaller than n_neighbors.
  71. alpha: float in (0., 1.), optional (default=0.8)
  72. specifies the lower limit for selecting subspace.
  73. 0.8 is set as default as suggested in the original paper.
  74. contamination : float in (0., 0.5), optional (default=0.1)
  75. The amount of contamination of the data set, i.e.
  76. the proportion of outliers in the data set. Used when fitting to
  77. define the threshold on the decision function.
  78. Attributes
  79. ----------
  80. decision_scores_ : numpy array of shape (n_samples,)
  81. The outlier scores of the training data.
  82. The higher, the more abnormal. Outliers tend to have higher
  83. scores. This value is available once the detector is
  84. fitted.
  85. threshold_ : float
  86. The threshold is based on ``contamination``. It is the
  87. ``n_samples * contamination`` most abnormal samples in
  88. ``decision_scores_``. The threshold is calculated for generating
  89. binary outlier labels.
  90. labels_ : int, either 0 or 1
  91. The binary labels of the training data. 0 stands for inliers
  92. and 1 for outliers/anomalies. It is generated by applying
  93. ``threshold_`` on ``decision_scores_``.
  94. """
  95. metadata = metadata_base.PrimitiveMetadata({
  96. "__author__": "DATA Lab at Texas A&M University",
  97. "name": "Subspace Outlier Detection Primitive",
  98. "python_path": "d3m.primitives.tods.detection_algorithm.pyod_sod",
  99. "source": {'name': 'DATA Lab at Texas A&M University', 'contact': 'mailto:khlai037@tamu.edu',
  100. 'uris': ['https://gitlab.com/lhenry15/tods.git', 'https://gitlab.com/lhenry15/tods/-/blob/Yile/anomaly-primitives/anomaly_primitives/PyodSOD.py']},
  101. "algorithm_types": [metadata_base.PrimitiveAlgorithmType.SUBSPACE_OUTLIER_DETECTION],
  102. "primitive_family": metadata_base.PrimitiveFamily.ANOMALY_DETECTION,
  103. "id": str(uuid.uuid3(uuid.NAMESPACE_DNS, 'SODPrimitive')),
  104. "hyperparams_to_tune": ['contamination', 'n_neighbors', 'ref_set', 'alpha'],
  105. "version": "0.0.1",
  106. })
  107. def __init__(self, *,
  108. hyperparams: Hyperparams, #
  109. random_seed: int = 0,
  110. docker_containers: Dict[str, DockerContainer] = None) -> None:
  111. super().__init__(hyperparams=hyperparams, random_seed=random_seed, docker_containers=docker_containers)
  112. self._clf = SOD(contamination=hyperparams['contamination'],
  113. n_neighbors=hyperparams['n_neighbors'],
  114. ref_set=hyperparams['ref_set'],
  115. alpha=hyperparams['alpha'],
  116. )
  117. def set_training_data(self, *, inputs: Inputs) -> None:
  118. """
  119. Set training data for outlier detection.
  120. Args:
  121. inputs: Container DataFrame
  122. Returns:
  123. None
  124. """
  125. super().set_training_data(inputs=inputs)
  126. def fit(self, *, timeout: float = None, iterations: int = None) -> CallResult[None]:
  127. """
  128. Fit model with training data.
  129. Args:
  130. *: Container DataFrame. Time series data up to fit.
  131. Returns:
  132. None
  133. """
  134. return super().fit()
  135. def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> CallResult[Outputs]:
  136. """
  137. Process the testing data.
  138. Args:
  139. inputs: Container DataFrame. Time series data up to outlier detection.
  140. Returns:
  141. Container DataFrame
  142. 1 marks Outliers, 0 marks normal.
  143. """
  144. return super().produce(inputs=inputs, timeout=timeout, iterations=iterations)
  145. def get_params(self) -> Params:
  146. """
  147. Return parameters.
  148. Args:
  149. None
  150. Returns:
  151. class Params
  152. """
  153. return super().get_params()
  154. def set_params(self, *, params: Params) -> None:
  155. """
  156. Set parameters for outlier detection.
  157. Args:
  158. params: class Params
  159. Returns:
  160. None
  161. """
  162. super().set_params(params=params)

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