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.

MultiAutoRegOD.py 8.3 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # -*- coding: utf-8 -*-
  2. """Autoregressive model for multivariate time series outlier detection.
  3. """
  4. import numpy as np
  5. from sklearn.utils import check_array
  6. from sklearn.utils.validation import check_is_fitted
  7. from sklearn.utils import column_or_1d
  8. from detection_algorithm.core.CollectiveBase import CollectiveBaseDetector
  9. from combo.models.score_comb import average, maximization, median, aom, moa
  10. from combo.utils.utility import standardizer
  11. from detection_algorithm.core.AutoRegOD import AutoRegOD
  12. from detection_algorithm.core.utility import get_sub_sequences_length
  13. class MultiAutoRegOD(CollectiveBaseDetector):
  14. """Autoregressive models use linear regression to calculate a sample's
  15. deviance from the predicted value, which is then used as its
  16. outlier scores. This model is for multivariate time series.
  17. This model handles multivariate time series by various combination
  18. approaches. See AutoRegOD for univarite data.
  19. See :cite:`aggarwal2015outlier,zhao2020using` for details.
  20. Parameters
  21. ----------
  22. window_size : int
  23. The moving window size.
  24. step_size : int, optional (default=1)
  25. The displacement for moving window.
  26. contamination : float in (0., 0.5), optional (default=0.1)
  27. The amount of contamination of the data set, i.e.
  28. the proportion of outliers in the data set. When fitting this is used
  29. to define the threshold on the decision function.
  30. method : str, optional (default='average')
  31. Combination method: {'average', 'maximization',
  32. 'median'}. Pass in weights of detector for weighted version.
  33. weights : numpy array of shape (1, n_dimensions)
  34. Score weight by dimensions.
  35. Attributes
  36. ----------
  37. decision_scores_ : numpy array of shape (n_samples,)
  38. The outlier scores of the training data.
  39. The higher, the more abnormal. Outliers tend to have higher
  40. scores. This value is available once the detector is
  41. fitted.
  42. labels_ : int, either 0 or 1
  43. The binary labels of the training data. 0 stands for inliers
  44. and 1 for outliers/anomalies. It is generated by applying
  45. ``threshold_`` on ``decision_scores_``.
  46. """
  47. def __init__(self, window_size, step_size=1, method='average',
  48. weights=None, contamination=0.1):
  49. super(MultiAutoRegOD, self).__init__(contamination=contamination)
  50. self.window_size = window_size
  51. self.step_size = step_size
  52. self.method = method
  53. self.weights = weights
  54. def _validate_weights(self):
  55. """Internal function for validating and adjust weights.
  56. Returns
  57. -------
  58. """
  59. if self.weights is None:
  60. self.weights = np.ones([1, self.n_models_])
  61. else:
  62. self.weights = column_or_1d(self.weights).reshape(
  63. 1, len(self.weights))
  64. assert (self.weights.shape[1] == self.n_models_)
  65. # adjust probability by a factor for integrity
  66. adjust_factor = self.weights.shape[1] / np.sum(self.weights)
  67. self.weights = self.weights * adjust_factor
  68. def _fit_univariate_model(self, X):
  69. """Internal function for fitting one dimensional ts.
  70. """
  71. X = check_array(X)
  72. n_samples, n_sequences = X.shape[0], X.shape[1]
  73. models = []
  74. # train one model for each dimension
  75. for i in range(n_sequences):
  76. models.append(AutoRegOD(window_size=self.window_size,
  77. step_size=self.step_size,
  78. contamination=self.contamination))
  79. models[i].fit(X[:, i].reshape(-1, 1))
  80. return models
  81. def _score_combination(self, scores):
  82. """Internal function for combining univarite scores.
  83. """
  84. # combine by different approaches
  85. if self.method == 'average':
  86. return average(scores, estimator_weights=self.weights)
  87. if self.method == 'maximization':
  88. return maximization(scores)
  89. if self.method == 'median':
  90. return median(scores)
  91. def fit(self, X: np.array) -> object:
  92. """Fit detector. y is ignored in unsupervised methods.
  93. Parameters
  94. ----------
  95. X : numpy array of shape (n_samples, n_features)
  96. The input samples.
  97. y : Ignored
  98. Not used, present for API consistency by convention.
  99. Returns
  100. -------
  101. self : object
  102. Fitted estimator.
  103. """
  104. X = check_array(X).astype(np.float)
  105. # fit each dimension individually
  106. self.models_ = self._fit_univariate_model(X)
  107. self.valid_len_ = self.models_[0].valid_len_
  108. self.n_models_ = len(self.models_)
  109. # assign the left and right inds, same for all models
  110. self.left_inds_ = self.models_[0].left_inds_
  111. self.right_inds_ = self.models_[0].right_inds_
  112. # validate and adjust weights
  113. self._validate_weights()
  114. # combine the scores from all dimensions
  115. self._decison_mat = np.zeros([self.valid_len_, self.n_models_])
  116. for i in range(self.n_models_):
  117. self._decison_mat[:, i] = self.models_[i].decision_scores_
  118. # scale scores by standardization before score combination
  119. self._decison_mat_scalaled, self._score_scalar = standardizer(
  120. self._decison_mat, keep_scalar=True)
  121. self.decision_scores_ = self._score_combination(
  122. self._decison_mat_scalaled)
  123. self._process_decision_scores()
  124. return self
  125. def decision_function(self, X: np.array):
  126. """Predict raw anomaly scores of X using the fitted detector.
  127. The anomaly score of an input sample is computed based on the fitted
  128. detector. For consistency, outliers are assigned with
  129. higher anomaly scores.
  130. Parameters
  131. ----------
  132. X : numpy array of shape (n_samples, n_features)
  133. The input samples. Sparse matrices are accepted only
  134. if they are supported by the base estimator.
  135. Returns
  136. -------
  137. anomaly_scores : numpy array of shape (n_samples,)
  138. The anomaly score of the input samples.
  139. """
  140. check_is_fitted(self, ['models_'])
  141. X = check_array(X).astype(np.float)
  142. assert (X.shape[1] == self.n_models_)
  143. n_samples = len(X)
  144. # need to subtract 1 because need to have y for subtraction
  145. valid_len = get_sub_sequences_length(n_samples, self.window_size,
  146. self.step_size) - 1
  147. # combine the scores from all dimensions
  148. decison_mat = np.zeros([valid_len, self.n_models_])
  149. for i in range(self.n_models_):
  150. decison_mat[:, i], X_left_inds, X_right_inds = \
  151. self.models_[i].decision_function(X[:, i].reshape(-1, 1))
  152. # scale the decision mat
  153. decison_mat_scaled = self._score_scalar.transform(decison_mat)
  154. decision_scores = self._score_combination(decison_mat_scaled)
  155. return decision_scores, X_left_inds, X_right_inds
  156. if __name__ == "__main__":
  157. X_train = np.asarray(
  158. [[3., 5], [5., 9], [7., 2], [42., 20], [8., 12], [10., 12], [12., 12],
  159. [18., 16], [20., 7], [18., 10], [23., 12], [22., 15]])
  160. X_test = np.asarray(
  161. [[3., 5], [5., 9], [7., 2], [42., 20], [8., 12], [10., 12], [12., 12],
  162. [18., 16], [20., 7], [18., 10], [23., 12], [22., 15]])
  163. # X_test = np.asarray(
  164. # [[12., 10], [8., 12], [80., 80], [92., 983],
  165. # [18., 16], [20., 7], [18., 10], [3., 5], [5., 9], [23., 12],
  166. # [22., 15]])
  167. clf = MultiAutoRegOD(window_size=3, step_size=1, contamination=0.2)
  168. clf.fit(X_train)
  169. decision_scores, left_inds_, right_inds = clf.decision_scores_, \
  170. clf.left_inds_, clf.right_inds_
  171. print(clf.left_inds_, clf.right_inds_)
  172. pred_scores, X_left_inds, X_right_inds = clf.decision_function(X_test)
  173. pred_labels, X_left_inds, X_right_inds = clf.predict(X_test)
  174. pred_probs, X_left_inds, X_right_inds = clf.predict_proba(X_test)
  175. print(pred_scores)
  176. print(pred_labels)
  177. print(pred_probs)

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