-
Notifications
You must be signed in to change notification settings - Fork 55
/
MSCRED.py
356 lines (303 loc) · 10.3 KB
/
MSCRED.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import math
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.callbacks import ReduceLROnPlateau
from tensorflow.keras.layers import (
Conv2D,
Conv2DTranspose,
ConvLSTM2D,
Input,
Layer,
TimeDistributed,
)
from tensorflow.keras.optimizers import Adam
class MSCRED:
"""
MSCRED - Multi-Scale Convolutional Recurrent Encoder-Decoder first constructs multi-scale (resolution) signature matrices to characterize multiple levels of the system statuses across different time steps. In particular, different levels of the system statuses are used to indicate the severity of different abnormal incidents. Subsequently, given the signature matrices, a convolutional encoder is employed to encode the inter-sensor (time series) correlations patterns and an attention based Convolutional Long-Short Term Memory (ConvLSTM) network is developed to capture the temporal patterns. Finally, with the feature maps which encode the inter-sensor correlations and temporal information, a convolutional decoder is used to reconstruct the signature matrices and the residual signature matrices are further utilized to detect and diagnose anomalies. The intuition is that MSCRED may not reconstruct the signature matrices well if it never observes similar system statuses before.
Parameters
----------
params : list
A list containing configuration parameters for the MSCRED model.
Attributes
----------
model : Model
The trained MSCRED model.
Examples
--------
>>> from MSCRED import MSCRED
>>> PARAMS = [sensor_n, scale_n, step_max]
>>> model = MSCRED(PARAMS)
>>> model.fit(X_train, Y_train, X_test, Y_test)
>>> prediction = model.predict(test_data)
"""
def __init__(self, params):
self.params = params
def _build_model(self):
self._Random(0)
class MyPadLayer(Layer):
def __init__(self, paddings, **kwargs):
super().__init__(**kwargs)
self.paddings = paddings
def call(self, inputs):
return tf.pad(inputs, self.paddings)
class MyAttentionLayer(Layer):
def __init__(self, attention_fun, **kwargs):
super().__init__(**kwargs)
self.attention = attention_fun
def call(self, inputs, **kwargs):
# Your attention mechanism implementation here
return self.attention(inputs, **kwargs)
class MyConcatLayer(Layer):
def __init__(self, axis, **kwargs):
super().__init__(**kwargs)
self.axis = axis
def call(self, inputs):
return tf.concat(inputs, axis=self.axis)
input_size = (
self.params[2],
self.params[0],
self.params[0],
self.params[1],
)
inputs = Input(input_size)
if self.params[0] % 8 != 0:
self.sensor_n_pad = (self.params[0] // 8) * 8 + 8
else:
self.sensor_n_pad = self.params[0]
paddings = tf.constant(
[
[0, 0],
[0, 0],
[0, self.sensor_n_pad - self.params[0]],
[0, self.sensor_n_pad - self.params[0]],
[0, 0],
]
)
inputs_pad = MyPadLayer(paddings)(inputs)
conv1 = TimeDistributed(
Conv2D(
filters=32,
kernel_size=3,
strides=1,
kernel_initializer="glorot_uniform",
padding="same",
activation="selu",
name="conv1",
)
)(inputs_pad)
conv2 = TimeDistributed(
Conv2D(
filters=64,
kernel_size=3,
strides=2,
kernel_initializer="glorot_uniform",
padding="same",
activation="selu",
name="conv2",
)
)(conv1)
conv3 = TimeDistributed(
Conv2D(
filters=128,
kernel_size=2,
strides=2,
kernel_initializer="glorot_uniform",
padding="same",
activation="selu",
name="conv3",
)
)(conv2)
conv4 = TimeDistributed(
Conv2D(
filters=256,
kernel_size=2,
strides=2,
kernel_initializer="glorot_uniform",
padding="same",
activation="selu",
name="conv4",
)
)(conv3)
convLSTM1 = ConvLSTM2D(
filters=32,
kernel_size=2,
padding="same",
return_sequences=True,
name="convLSTM1",
)(conv1)
convLSTM1_out = MyAttentionLayer(self.attention)(
convLSTM1, **{"koef": 1}
)
convLSTM2 = ConvLSTM2D(
filters=64,
kernel_size=2,
padding="same",
return_sequences=True,
name="convLSTM2",
)(conv2)
convLSTM2_out = MyAttentionLayer(self.attention)(
convLSTM2, **{"koef": 2}
)
convLSTM3 = ConvLSTM2D(
filters=128,
kernel_size=2,
padding="same",
return_sequences=True,
name="convLSTM3",
)(conv3)
convLSTM3_out = MyAttentionLayer(self.attention)(
convLSTM3, **{"koef": 4}
)
convLSTM4 = ConvLSTM2D(
filters=256,
kernel_size=2,
padding="same",
return_sequences=True,
name="convLSTM4",
)(conv4)
convLSTM4_out = MyAttentionLayer(self.attention)(
convLSTM4, **{"koef": 8}
)
deconv4 = Conv2DTranspose(
filters=128,
kernel_size=2,
strides=2,
kernel_initializer="glorot_uniform",
padding="same",
activation="selu",
name="deconv4",
)(convLSTM4_out)
deconv4_out = MyConcatLayer(axis=3)([deconv4, convLSTM3_out])
deconv3 = Conv2DTranspose(
filters=64,
kernel_size=2,
strides=2,
kernel_initializer="glorot_uniform",
padding="same",
activation="selu",
name="deconv3",
)(deconv4_out)
deconv3_out = MyConcatLayer(axis=3)([deconv3, convLSTM2_out])
deconv2 = Conv2DTranspose(
filters=32,
kernel_size=3,
strides=2,
kernel_initializer="glorot_uniform",
padding="same",
activation="selu",
name="deconv2",
)(deconv3_out)
deconv2_out = MyConcatLayer(axis=3)([deconv2, convLSTM1_out])
deconv1 = Conv2DTranspose(
filters=self.params[1],
kernel_size=3,
strides=1,
kernel_initializer="glorot_uniform",
padding="same",
activation="selu",
name="deconv1",
)(deconv2_out)
model = Model(
inputs=inputs,
outputs=deconv1[:, : self.params[0], : self.params[0], :],
)
return model
def attention(self, outputs, koef):
"""
Attention mechanism to weigh the importance of each step in the sequence.
Parameters
----------
outputs : tf.Tensor
The output tensor from ConvLSTM layers.
koef : int
A coefficient to scale the attention mechanism.
Returns
-------
tf.Tensor
Weighted output tensor.
"""
attention_w = []
for k in range(self.params[2]):
attention_w.append(
tf.reduce_sum(
tf.multiply(outputs[:, k], outputs[:, -1]), axis=(1, 2, 3)
)
/ self.params[2]
)
attention_w = tf.reshape(
tf.nn.softmax(tf.stack(attention_w, axis=1)),
[-1, 1, self.params[2]],
)
outputs = tf.reshape(
outputs,
[-1, self.params[2], tf.reduce_prod(outputs.shape.as_list()[2:])],
)
outputs = tf.matmul(attention_w, outputs)
outputs = tf.reshape(
outputs,
[
-1,
math.ceil(self.sensor_n_pad / koef),
math.ceil(self.sensor_n_pad / koef),
32 * koef,
],
)
return outputs
def _Random(self, seed_value):
import os
os.environ["PYTHONHASHSEED"] = str(seed_value)
import random
random.seed(seed_value)
import numpy as np
np.random.seed(seed_value)
import tensorflow as tf
tf.random.set_seed(seed_value)
def _loss_fn(self, y_true, y_pred):
return tf.reduce_mean(tf.square(y_true - y_pred))
def fit(self, X_train, Y_train, batch_size=200, epochs=25):
"""
Train the MSCRED model on the provided data.
Parameters
----------
X_train : numpy.ndarray
The training input data.
Y_train : numpy.ndarray
The training target data.
X_test : numpy.ndarray
The testing input data.
Y_test : numpy.ndarray
The testing target data.
batch_size : int, optional
The batch size for training, by default 200.
epochs : int, optional
The number of training epochs, by default 25.
"""
self.model = self._build_model()
self.model.compile(
optimizer=Adam(learning_rate=1e-3),
loss=self._loss_fn,
)
reduce_lr = ReduceLROnPlateau(
monitor="loss", factor=0.8, patience=6, min_lr=0.000001, verbose=1
)
self.model.fit(
X_train,
Y_train,
batch_size=batch_size,
epochs=epochs,
# validation_data=(X_test, Y_test),
callbacks=reduce_lr,
)
def predict(self, data):
"""
Generate predictions using the trained MSCRED model.
Parameters
----------
data : numpy.ndarray
Input data for generating predictions.
Returns
-------
numpy.ndarray
Predicted output data.
"""
return self.model.predict(data)