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.

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

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