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.

PyodLOF.py 12 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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.lof import LOF
  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_neighbors = hyperparams.Hyperparameter[int](
  42. default=20,
  43. description='Number of neighbors to use by default for `kneighbors` queries. If n_neighbors is larger than the number of samples provided, all samples will be used.',
  44. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  45. )
  46. algorithm = hyperparams.Enumeration[str](
  47. values=['auto', 'ball_tree', 'kd_tree', 'brute'],
  48. default='auto',
  49. description='Algorithm used to compute the nearest neighbors.',
  50. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  51. )
  52. leaf_size = hyperparams.Hyperparameter[int](
  53. default=30,
  54. description='Leaf size passed to `BallTree` or `KDTree`. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.',
  55. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  56. )
  57. metric = hyperparams.Enumeration[str](
  58. values=['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
  59. 'manhattan', 'braycurtis', 'canberra', 'chebyshev',
  60. 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
  61. 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto',
  62. 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath',
  63. 'sqeuclidean', 'yule'],
  64. default='minkowski',
  65. description='metric used for the distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used.',
  66. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  67. )
  68. p = hyperparams.Hyperparameter[int](
  69. default=2,
  70. description='Parameter for the Minkowski metric from.',
  71. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  72. )
  73. metric_params = hyperparams.Union[Union[Dict, None]](
  74. configuration=OrderedDict(
  75. init=hyperparams.Hyperparameter[Dict](
  76. default={},
  77. ),
  78. ninit=hyperparams.Hyperparameter[None](
  79. default=None,
  80. ),
  81. ),
  82. default='ninit',
  83. description='Additional keyword arguments for the metric function.',
  84. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
  85. )
  86. pass
  87. class LOFPrimitive(UnsupervisedOutlierDetectorBase[Inputs, Outputs, Params, Hyperparams]):
  88. """
  89. Wrapper of Pyod LOF Class with more functionalities.
  90. Unsupervised Outlier Detection using Local Outlier Factor (LOF).
  91. The anomaly score of each sample is called Local Outlier Factor.
  92. It measures the local deviation of density of a given sample with
  93. respect to its neighbors.
  94. It is local in that the anomaly score depends on how isolated the object
  95. is with respect to the surrounding neighborhood.
  96. More precisely, locality is given by k-nearest neighbors, whose distance
  97. is used to estimate the local density.
  98. By comparing the local density of a sample to the local densities of
  99. its neighbors, one can identify samples that have a substantially lower
  100. density than their neighbors. These are considered outliers.
  101. See :cite:`breunig2000lof` for details.
  102. Parameters
  103. ----------
  104. n_neighbors : int, optional (default=20)
  105. Number of neighbors to use by default for `kneighbors` queries.
  106. If n_neighbors is larger than the number of samples provided,
  107. all samples will be used.
  108. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional
  109. Algorithm used to compute the nearest neighbors:
  110. - 'ball_tree' will use BallTree
  111. - 'kd_tree' will use KDTree
  112. - 'brute' will use a brute-force search.
  113. - 'auto' will attempt to decide the most appropriate algorithm
  114. based on the values passed to :meth:`fit` method.
  115. Note: fitting on sparse input will override the setting of
  116. this parameter, using brute force.
  117. leaf_size : int, optional (default=30)
  118. Leaf size passed to `BallTree` or `KDTree`. This can
  119. affect the speed of the construction and query, as well as the memory
  120. required to store the tree. The optimal value depends on the
  121. nature of the problem.
  122. metric : string or callable, default 'minkowski'
  123. metric used for the distance computation. Any metric from scikit-learn
  124. or scipy.spatial.distance can be used.
  125. If 'precomputed', the training input X is expected to be a distance
  126. matrix.
  127. If metric is a callable function, it is called on each
  128. pair of instances (rows) and the resulting value recorded. The callable
  129. should take two arrays as input and return one value indicating the
  130. distance between them. This works for Scipy's metrics, but is less
  131. efficient than passing the metric name as a string.
  132. Valid values for metric are:
  133. - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
  134. 'manhattan']
  135. - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
  136. 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
  137. 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto',
  138. 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath',
  139. 'sqeuclidean', 'yule']
  140. See the documentation for scipy.spatial.distance for details on these
  141. metrics:
  142. http://docs.scipy.org/doc/scipy/reference/spatial.distance.html
  143. p : integer, optional (default = 2)
  144. Parameter for the Minkowski metric from
  145. sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is
  146. equivalent to using manhattan_distance (l1), and euclidean_distance
  147. (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
  148. See http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances
  149. metric_params : dict, optional (default = None)
  150. Additional keyword arguments for the metric function.
  151. contamination : float in (0., 0.5), optional (default=0.1)
  152. The amount of contamination of the data set, i.e. the proportion
  153. of outliers in the data set. When fitting this is used to define the
  154. threshold on the decision function.
  155. n_jobs : int, optional (default = 1)
  156. The number of parallel jobs to run for neighbors search.
  157. If ``-1``, then the number of jobs is set to the number of CPU cores.
  158. Affects only kneighbors and kneighbors_graph methods.
  159. Attributes
  160. ----------
  161. decision_scores_ : numpy array of shape (n_samples,)
  162. The outlier scores of the training data.
  163. The higher, the more abnormal. Outliers tend to have higher
  164. scores. This value is available once the detector is
  165. fitted.
  166. threshold_ : float
  167. The threshold is based on ``contamination``. It is the
  168. ``n_samples * contamination`` most abnormal samples in
  169. ``decision_scores_``. The threshold is calculated for generating
  170. binary outlier labels.
  171. labels_ : int, either 0 or 1
  172. The binary labels of the training data. 0 stands for inliers
  173. and 1 for outliers/anomalies. It is generated by applying
  174. ``threshold_`` on ``decision_scores_``.
  175. """
  176. metadata = metadata_base.PrimitiveMetadata({
  177. "name": "TODS.anomaly_detection_primitives.LOFPrimitive",
  178. "python_path": "d3m.primitives.tods.detection_algorithm.pyod_lof",
  179. "source": {'name': "DATALAB @Taxes A&M University", 'contact': 'mailto:khlai037@tamu.edu',
  180. 'uris': ['https://gitlab.com/lhenry15/tods.git']},
  181. "algorithm_types": [metadata_base.PrimitiveAlgorithmType.LOCAL_OUTLIER_FACTOR, ],
  182. "primitive_family": metadata_base.PrimitiveFamily.ANOMALY_DETECTION,
  183. "version": "0.0.1",
  184. "hyperparams_to_tune": ['n_neighbors', 'algorithm', 'leaf_size', 'p', 'contamination'],
  185. "id": str(uuid.uuid3(uuid.NAMESPACE_DNS, 'LOFPrimitive')),
  186. })
  187. def __init__(self, *,
  188. hyperparams: Hyperparams, #
  189. random_seed: int = 0,
  190. docker_containers: Dict[str, DockerContainer] = None) -> None:
  191. super().__init__(hyperparams=hyperparams, random_seed=random_seed, docker_containers=docker_containers)
  192. self._clf = LOF(contamination=hyperparams['contamination'],
  193. n_neighbors=hyperparams['n_neighbors'],
  194. algorithm=hyperparams['algorithm'],
  195. leaf_size=hyperparams['leaf_size'],
  196. metric=hyperparams['metric'],
  197. p=hyperparams['p'],
  198. metric_params=hyperparams['metric_params'],
  199. )
  200. return
  201. def set_training_data(self, *, inputs: Inputs) -> None:
  202. """
  203. Set training data for outlier detection.
  204. Args:
  205. inputs: Container DataFrame
  206. Returns:
  207. None
  208. """
  209. super().set_training_data(inputs=inputs)
  210. def fit(self, *, timeout: float = None, iterations: int = None) -> CallResult[None]:
  211. """
  212. Fit model with training data.
  213. Args:
  214. *: Container DataFrame. Time series data up to fit.
  215. Returns:
  216. None
  217. """
  218. return super().fit()
  219. def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> CallResult[Outputs]:
  220. """
  221. Process the testing data.
  222. Args:
  223. inputs: Container DataFrame. Time series data up to outlier detection.
  224. Returns:
  225. Container DataFrame
  226. 1 marks Outliers, 0 marks normal.
  227. """
  228. return super().produce(inputs=inputs, timeout=timeout, iterations=iterations)
  229. def get_params(self) -> Params:
  230. """
  231. Return parameters.
  232. Args:
  233. None
  234. Returns:
  235. class Params
  236. """
  237. return super().get_params()
  238. def set_params(self, *, params: Params) -> None:
  239. """
  240. Set parameters for outlier detection.
  241. Args:
  242. params: class Params
  243. Returns:
  244. None
  245. """
  246. super().set_params(params=params)

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