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.

PyodOCSVM.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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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.ocsvm import OCSVM
  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. kernel = hyperparams.Enumeration[str](
  42. values=['linear', 'poly', 'rbf', 'sigmoid', 'precomputed'],
  43. default='rbf',
  44. description='Specifies the kernel type to be used in the algorithm.',
  45. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  46. )
  47. nu = hyperparams.Uniform(
  48. lower=0.,
  49. upper=1.,
  50. default=0.5,
  51. description='An upper bound on the fraction of training errors and a lower bound of the fraction of support vectors.',
  52. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  53. )
  54. degree = hyperparams.Hyperparameter[int](
  55. default=3,
  56. description='Degree of the polynomial kernel function (poly). Ignored by all other kernels.',
  57. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  58. )
  59. gamma = hyperparams.Union[Union[float, str]](
  60. configuration=OrderedDict(
  61. init=hyperparams.Hyperparameter[float](
  62. default=0.,
  63. ),
  64. ninit=hyperparams.Hyperparameter[str](
  65. default='auto',
  66. ),
  67. ),
  68. default='ninit',
  69. description='Kernel coefficient for rbf, poly and sigmoid. If gamma is auto then 1/n_features will be used instead.',
  70. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
  71. )
  72. coef0 = hyperparams.Hyperparameter[float](
  73. default=0.,
  74. description='Independent term in kernel function. It is only significant in poly and sigmoid.',
  75. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  76. )
  77. tol = hyperparams.Hyperparameter[float](
  78. default=0.001,
  79. description='Tolerance for stopping criterion.',
  80. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  81. )
  82. shrinking = hyperparams.UniformBool(
  83. default=True,
  84. description='Whether to use the shrinking heuristic.',
  85. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  86. )
  87. cache_size = hyperparams.Hyperparameter[int](
  88. default=200,
  89. description='Specify the size of the kernel cache (in MB).',
  90. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  91. )
  92. verbose = hyperparams.UniformBool(
  93. default=False,
  94. description='Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context.',
  95. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  96. )
  97. max_iter = hyperparams.Hyperparameter[int](
  98. default=-1,
  99. description='Hard limit on iterations within solver, or -1 for no limit.',
  100. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']
  101. )
  102. pass
  103. class OCSVMPrimitive(UnsupervisedOutlierDetectorBase[Inputs, Outputs, Params, Hyperparams]):
  104. """
  105. Wrapper of scikit-learn one-class SVM Class with more functionalities.
  106. Unsupervised Outlier Detection.
  107. Estimate the support of a high-dimensional distribution.
  108. The implementation is based on libsvm.
  109. See http://scikit-learn.org/stable/modules/svm.html#svm-outlier-detection
  110. and :cite:`scholkopf2001estimating`.
  111. Parameters
  112. ----------
  113. kernel : string, optional (default='rbf')
  114. Specifies the kernel type to be used in the algorithm.
  115. It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or
  116. a callable.
  117. If none is given, 'rbf' will be used. If a callable is given it is
  118. used to precompute the kernel matrix.
  119. nu : float, optional
  120. An upper bound on the fraction of training
  121. errors and a lower bound of the fraction of support
  122. vectors. Should be in the interval (0, 1]. By default 0.5
  123. will be taken.
  124. degree : int, optional (default=3)
  125. Degree of the polynomial kernel function ('poly').
  126. Ignored by all other kernels.
  127. gamma : float, optional (default='auto')
  128. Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.
  129. If gamma is 'auto' then 1/n_features will be used instead.
  130. coef0 : float, optional (default=0.0)
  131. Independent term in kernel function.
  132. It is only significant in 'poly' and 'sigmoid'.
  133. tol : float, optional
  134. Tolerance for stopping criterion.
  135. shrinking : bool, optional
  136. Whether to use the shrinking heuristic.
  137. cache_size : float, optional
  138. Specify the size of the kernel cache (in MB).
  139. verbose : bool, default: False
  140. Enable verbose output. Note that this setting takes advantage of a
  141. per-process runtime setting in libsvm that, if enabled, may not work
  142. properly in a multithreaded context.
  143. max_iter : int, optional (default=-1)
  144. Hard limit on iterations within solver, or -1 for no limit.
  145. Attributes
  146. ----------
  147. decision_scores_ : numpy array of shape (n_samples,)
  148. The outlier scores of the training data.
  149. The higher, the more abnormal. Outliers tend to have higher
  150. scores. This value is available once the detector is fitted.
  151. threshold_ : float
  152. The threshold is based on ``contamination``. It is the
  153. ``n_samples * contamination`` most abnormal samples in
  154. ``decision_scores_``. The threshold is calculated for generating
  155. binary outlier labels.
  156. labels_ : int, either 0 or 1
  157. The binary labels of the training data. 0 stands for inliers
  158. and 1 for outliers/anomalies. It is generated by applying
  159. ``threshold_`` on ``decision_scores_``.
  160. """
  161. metadata = metadata_base.PrimitiveMetadata({
  162. "name": "TODS.anomaly_detection_primitives.OCSVMPrimitive",
  163. "python_path": "d3m.primitives.tods.detection_algorithm.pyod_ocsvm",
  164. "source": {'name': "DATALAB @Taxes A&M University", 'contact': 'mailto:khlai037@tamu.edu',
  165. 'uris': ['https://gitlab.com/lhenry15/tods.git']},
  166. "algorithm_types": [metadata_base.PrimitiveAlgorithmType.MARGIN_CLASSIFIER, ],
  167. "primitive_family": metadata_base.PrimitiveFamily.ANOMALY_DETECTION,
  168. "version": "0.0.1",
  169. "hyperparams_to_tune": ['contamination', 'kernel', 'nu', 'gamma', 'degree'],
  170. "id": str(uuid.uuid3(uuid.NAMESPACE_DNS, 'OCSVMPrimitive'))
  171. })
  172. def __init__(self, *,
  173. hyperparams: Hyperparams, #
  174. random_seed: int = 0,
  175. docker_containers: Dict[str, DockerContainer] = None) -> None:
  176. super().__init__(hyperparams=hyperparams, random_seed=random_seed, docker_containers=docker_containers)
  177. self._clf = OCSVM(contamination=hyperparams['contamination'],
  178. kernel=hyperparams['kernel'],
  179. nu=hyperparams['nu'],
  180. degree=hyperparams['degree'],
  181. gamma=hyperparams['gamma'],
  182. coef0=hyperparams['coef0'],
  183. tol=hyperparams['tol'],
  184. shrinking=hyperparams['shrinking'],
  185. cache_size=hyperparams['cache_size'],
  186. verbose=hyperparams['verbose'],
  187. max_iter=hyperparams['max_iter'],
  188. )
  189. return
  190. def set_training_data(self, *, inputs: Inputs) -> None:
  191. """
  192. Set training data for outlier detection.
  193. Args:
  194. inputs: Container DataFrame
  195. Returns:
  196. None
  197. """
  198. super().set_training_data(inputs=inputs)
  199. def fit(self, *, timeout: float = None, iterations: int = None) -> CallResult[None]:
  200. """
  201. Fit model with training data.
  202. Args:
  203. *: Container DataFrame. Time series data up to fit.
  204. Returns:
  205. None
  206. """
  207. return super().fit()
  208. def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> CallResult[Outputs]:
  209. """
  210. Process the testing data.
  211. Args:
  212. inputs: Container DataFrame. Time series data up to outlier detection.
  213. Returns:
  214. Container DataFrame
  215. 1 marks Outliers, 0 marks normal.
  216. """
  217. return super().produce(inputs=inputs, timeout=timeout, iterations=iterations)
  218. def get_params(self) -> Params:
  219. """
  220. Return parameters.
  221. Args:
  222. None
  223. Returns:
  224. class Params
  225. """
  226. return super().get_params()
  227. def set_params(self, *, params: Params) -> None:
  228. """
  229. Set parameters for outlier detection.
  230. Args:
  231. params: class Params
  232. Returns:
  233. None
  234. """
  235. super().set_params(params=params)

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