-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathConv_AE.py
131 lines (107 loc) · 3.37 KB
/
Conv_AE.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
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.layers import Conv1D, Conv1DTranspose, Dropout, Input
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
class Conv_AE:
"""
A reconstruction convolutional autoencoder model to detect anomalies in timeseries data using reconstruction error as an anomaly score.
Parameters
----------
No parameters are required for initializing the class.
Attributes
----------
model : Sequential
The trained convolutional autoencoder model.
Examples
--------
>>> from Conv_AE import Conv_AE
>>> CAutoencoder = Conv_AE()
>>> CAutoencoder.fit(train_data)
>>> prediction = CAutoencoder.predict(test_data)
"""
def __init__(self):
self._Random(0)
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 _build_model(self):
model = Sequential(
[
Input(shape=(self.shape[1], self.shape[2])),
Conv1D(
filters=32,
kernel_size=7,
padding="same",
strides=2,
activation="relu",
),
Dropout(rate=0.2),
Conv1D(
filters=16,
kernel_size=7,
padding="same",
strides=2,
activation="relu",
),
Conv1DTranspose(
filters=16,
kernel_size=7,
padding="same",
strides=2,
activation="relu",
),
Dropout(rate=0.2),
Conv1DTranspose(
filters=32,
kernel_size=7,
padding="same",
strides=2,
activation="relu",
),
Conv1DTranspose(filters=1, kernel_size=7, padding="same"),
]
)
model.compile(optimizer=Adam(learning_rate=0.001), loss="mse")
return model
def fit(self, data):
"""
Train the convolutional autoencoder model on the provided data.
Parameters
----------
data : numpy.ndarray
Input data for training the autoencoder model.
"""
self.shape = data.shape
self.model = self._build_model()
self.model.fit(
data,
data,
epochs=100,
batch_size=32,
validation_split=0.1,
verbose=0,
callbacks=[
EarlyStopping(
monitor="val_loss", patience=5, mode="min", verbose=0
)
],
)
def predict(self, data):
"""
Generate predictions using the trained convolutional autoencoder model.
Parameters
----------
data : numpy.ndarray
Input data for generating predictions.
Returns
-------
numpy.ndarray
Predicted output data.
"""
return self.model.predict(data)