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.

LSTMOD.py 9.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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. # -*- coding: utf-8 -*-
  2. """Autoregressive model for univariate 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 scipy.special import erf
  8. from sklearn.preprocessing import MinMaxScaler
  9. from detection_algorithm.core.CollectiveBase import CollectiveBaseDetector
  10. # from tod.utility import get_sub_matrices
  11. from keras.layers import Dense, LSTM
  12. from keras.models import Sequential
  13. class LSTMOutlierDetector(CollectiveBaseDetector):
  14. def __init__(self,contamination=0.1,
  15. train_contamination=0.0,
  16. min_attack_time=5,
  17. danger_coefficient_weight=0.5,
  18. loss='mean_squared_error',
  19. optimizer='adam',
  20. epochs=10,
  21. batch_size=8,
  22. dropout_rate=0.0,
  23. feature_dim=1,
  24. hidden_dim=8,
  25. n_hidden_layer=0,
  26. activation=None,
  27. diff_group_method='average'
  28. ):
  29. super(LSTMOutlierDetector, self).__init__(contamination=contamination,
  30. window_size=min_attack_time,
  31. step_size=1,
  32. )
  33. self.train_contamination = train_contamination
  34. self.min_attack_time = min_attack_time
  35. self.danger_coefficient_weight = danger_coefficient_weight
  36. self.relative_error_threshold = None
  37. self.loss = loss
  38. self.optimizer = optimizer
  39. self.epochs = epochs
  40. self.batch_size = batch_size
  41. self.dropout_rate = dropout_rate
  42. self.feature_dim = feature_dim
  43. self.hidden_dim = hidden_dim
  44. self.n_hidden_layer = n_hidden_layer
  45. self.diff_group_method = diff_group_method
  46. self.model_ = Sequential()
  47. self.model_.add(LSTM(units=hidden_dim, input_shape=(feature_dim, 1),
  48. dropout=dropout_rate, activation=activation))
  49. for layer_idx in range(n_hidden_layer):
  50. self.model_.add(LSTM(units=hidden_dim, input_shape=(hidden_dim, 1),
  51. dropout=dropout_rate, activation=activation))
  52. self.model_.add(Dense(units=feature_dim, input_shape=(hidden_dim, 1), activation=None))
  53. self.model_.compile(loss=self.loss, optimizer=self.optimizer)
  54. def fit(self, X: np.array, y=None) -> object:
  55. """Fit detector. y is ignored in unsupervised methods.
  56. Parameters
  57. ----------
  58. X : numpy array of shape (n_samples, n_features)
  59. The input samples.
  60. y : Ignored
  61. Not used, present for API consistency by convention.
  62. Returns
  63. -------
  64. self : object
  65. Fitted estimator.
  66. """
  67. X = check_array(X).astype(np.float)
  68. self._set_n_classes(None)
  69. X_buf, y_buf = self._get_sub_matrices(X)
  70. # fit the LSTM model
  71. self.model_.fit(X_buf, y_buf, epochs=self.epochs, batch_size=self.batch_size)
  72. relative_error = self._relative_error(X)
  73. if self.train_contamination < 1e-6:
  74. self.relative_error_threshold = max(relative_error)
  75. else:
  76. self.relative_error_threshold = np.percentile(relative_error, 100 * (1 - self.train_contamination))
  77. self.decision_scores_, self.left_inds_, self.right_inds_ = self.decision_function(X)
  78. self._process_decision_scores()
  79. return self
  80. def _get_sub_matrices(self, X: np.array):
  81. # return X[:-1].reshape(-1, 1, self.feature_dim), X[1:]
  82. return np.expand_dims(X[:-1], axis=2), X[1:]
  83. def _relative_error(self, X: np.array):
  84. X = check_array(X).astype(np.float)
  85. X_buf, y_buf = self._get_sub_matrices(X)
  86. y_predict = self.model_.predict(X_buf)
  87. relative_error = (np.linalg.norm(y_predict - y_buf, axis=1) / np.linalg.norm(y_buf + 1e-6, axis=1)).ravel()
  88. return relative_error
  89. def decision_function(self, X: np.array):
  90. """Predict raw anomaly scores of X using the fitted detector.
  91. The anomaly score of an input sample is computed based on the fitted
  92. detector. For consistency, outliers are assigned with
  93. higher anomaly scores.
  94. Parameters
  95. ----------
  96. X : numpy array of shape (n_samples, n_features)
  97. The input samples. Sparse matrices are accepted only
  98. if they are supported by the base estimator.
  99. Returns
  100. -------
  101. anomaly_scores : numpy array of shape (n_samples,)
  102. The anomaly score of the input samples.
  103. """
  104. check_is_fitted(self, ['model_'])
  105. relative_error = self._relative_error(X)
  106. error_num_buf = (relative_error > self.relative_error_threshold).astype(int)
  107. if not (self.diff_group_method in ['max', 'min', 'average']):
  108. raise ValueError(self.diff_group_method, "is not a valid method")
  109. relative_error_left_inds = np.ones((len(relative_error), )) * len(relative_error)
  110. relative_error_right_inds = np.zeros((len(relative_error), ))
  111. if self.diff_group_method == 'average':
  112. danger_coefficient = np.zeros(relative_error.shape)
  113. averaged_relative_error = np.zeros(relative_error.shape)
  114. calculated_times = np.zeros(relative_error.shape)
  115. for i in range(len(relative_error) - self.min_attack_time + 1):
  116. dc_tmp = error_num_buf[i:i+self.min_attack_time].sum() / self.min_attack_time
  117. are_tmp = relative_error[i:i+self.min_attack_time].sum() / self.min_attack_time
  118. for j in range(self.min_attack_time):
  119. averaged_relative_error[i + j] += are_tmp
  120. danger_coefficient[i + j] += dc_tmp
  121. calculated_times[i + j] += 1
  122. relative_error_left_inds[i + j] = i if i < relative_error_left_inds[i + j] else relative_error_left_inds[i + j]
  123. relative_error_right_inds[i + j] = i+self.min_attack_time if i+self.min_attack_time > relative_error_right_inds[i + j] else relative_error_left_inds[i + j]
  124. # print(calculated_times)
  125. danger_coefficient /= calculated_times
  126. averaged_relative_error /= calculated_times
  127. # print(danger_coefficient, averaged_relative_error)
  128. else:
  129. danger_coefficient = np.zeros(relative_error.shape)
  130. averaged_relative_error = np.zeros(relative_error.shape)
  131. if self.diff_group_method == 'min':
  132. danger_coefficient += float('inf')
  133. averaged_relative_error += float('inf')
  134. for i in range(len(relative_error) - self.min_attack_time + 1):
  135. dc_tmp = error_num_buf[i:i+self.min_attack_time].sum() / self.min_attack_time
  136. are_tmp = relative_error[i:i+self.min_attack_time].sum() / self.min_attack_time
  137. if self.diff_group_method == 'max':
  138. for j in range(self.min_attack_time):
  139. if are_tmp > averaged_relative_error[i + j] or dc_tmp > danger_coefficient[i+j]:
  140. relative_error_left_inds[i + j] = i
  141. relative_error_right_inds[i + j] = i+self.min_attack_time
  142. if are_tmp > averaged_relative_error[i + j]:
  143. averaged_relative_error[i + j] = are_tmp
  144. if dc_tmp > danger_coefficient[i+j]:
  145. danger_coefficient[i + j] = dc_tmp
  146. else:
  147. for j in range(self.min_attack_time):
  148. if are_tmp < averaged_relative_error[i + j] or dc_tmp < danger_coefficient[i+j]:
  149. relative_error_left_inds[i + j] = i
  150. relative_error_right_inds[i + j] = i+self.min_attack_time
  151. if are_tmp < averaged_relative_error[i + j]:
  152. averaged_relative_error[i + j] = are_tmp
  153. if dc_tmp < danger_coefficient[i+j]:
  154. danger_coefficient[i + j] = dc_tmp
  155. # print(relative_error_left_inds)
  156. # print(relative_error_right_inds)
  157. pred_score = danger_coefficient * self.danger_coefficient_weight + averaged_relative_error * (1 - self.danger_coefficient_weight)
  158. return pred_score, relative_error_left_inds, relative_error_right_inds
  159. if __name__ == "__main__":
  160. X_train = np.asarray(
  161. [3., 4., 8., 16, 18, 13., 22., 36., 59., 128, 62, 67, 78, 100]).reshape(-1, 1)
  162. X_test = np.asarray(
  163. [3., 4., 8.6, 13.4, 22.5, 17, 19.2, 36.1, 127, -23, 59.2]).reshape(-1,1)
  164. # print(X_train.shape, X_test.shape)
  165. clf = LSTMOutlierDetector(contamination=0.1)
  166. clf.fit(X_train)
  167. # pred_scores = clf.decision_function(X_test)
  168. pred_labels, left_inds, right_inds = clf.predict(X_test)
  169. print(pred_labels.shape, left_inds.shape, right_inds.shape)
  170. print(clf.threshold_)
  171. # print(np.percentile(pred_scores, 100 * 0.9))
  172. # print('pred_scores: ',pred_scores)
  173. print('pred_labels: ',pred_labels)

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