-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathanomaly_benchmark_processing.py
More file actions
212 lines (164 loc) · 5.77 KB
/
anomaly_benchmark_processing.py
File metadata and controls
212 lines (164 loc) · 5.77 KB
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
def detect_anomalies_in_data(
epochs, data_path, image_name, train_end, anomaly_start, anomaly_end
):
import os
import sys
sys.path.insert(0, os.path.abspath(".."))
import importlib
import samay.model
import src.samay.model
from src.samay.model import LPTMModel
importlib.reload(samay.model)
# -----------------------------------------
# LOADING THE MODEL
print("Using model.py from:", src.samay.model.__file__)
config = {
"task_name": "forecasting",
"forecast_horizon": 192,
"head_dropout": 0,
"weight_decay": 0,
"max_patch": 16,
"freeze_encoder": True, # Freeze the patch embedding layer
"freeze_embedder": True, # Freeze the transformer encoder
"freeze_head": False, # The linear forecasting head must be trained
"freeze_segment": True, # Freeze the segmention module
}
model = LPTMModel(config)
# -----------------------------------------
# TRAIN THE MODEL
from src.samay.anomaly_dataset_script import LPTMDataset
dataset_path = data_path
train_len = train_end
train_dataset = LPTMDataset(
name="ett",
datetime_col=None,
path=dataset_path,
mode="train",
horizon=192,
boundaries=[train_len, 0, 0],
bypass=2,
)
if epochs != 0:
finetuned_model = model.finetune(train_dataset, epoch=epochs)
# -----------------------------------------
# TEST THE MODEL
import pandas as pd
import plotly.graph_objects as go
import plotly.io as pio
pio.renderers.default = "browser"
df = pd.read_csv(dataset_path)
n = len(df)
print(n)
dataset = LPTMDataset(
name="ett",
datetime_col=None,
path=dataset_path,
mode="test",
horizon=192,
boundaries=[train_len, 0, n],
stride=10,
# seq_len=512,
task_name="forecasting",
bypass=2,
)
avg_loss, trues, preds, histories = model.evaluate(dataset, task_name="forecasting")
# -----------------------------------------
# PLOT AND SAVE THE RESULTS
import numpy as np
trues = np.array(trues)
preds = np.array(preds)
histories = np.array(histories)
"""for i in range(trues.shape[0]): # num_windows
for j in range(trues.shape[1]): # num_channels
trues[i, j, :] = scaler.inverse_transform(trues[i, j, :].reshape(-1, 1)).flatten()
preds[i, j, :] = scaler.inverse_transform(preds[i, j, :].reshape(-1, 1)).flatten()
histories[i, j, :] = scaler.inverse_transform(histories[i, j, :].reshape(-1, 1)).flatten()"""
# --- Parameters ---
stride = 10
num_windows, num_channels, forecast_len = preds.shape
first_k = stride
total_len = (num_windows - 1) * stride + first_k + histories.shape[-1]
stitched_true = np.zeros((num_channels, total_len))
stitched_pred = np.zeros((num_channels, total_len))
for i in range(num_windows):
start = i * stride
stitched_true[
:, start + histories.shape[-1] : start + histories.shape[-1] + first_k
] = trues[i, :, :first_k]
stitched_pred[
:, start + histories.shape[-1] : start + histories.shape[-1] + first_k
] = preds[i, :, :first_k]
channel_idx = 0
x = np.arange(stitched_true.shape[1])
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=x,
y=stitched_true[channel_idx],
mode="lines",
name="Ground Truth",
line=dict(color="darkblue"),
)
)
fig.add_trace(
go.Scatter(
x=x,
y=stitched_pred[channel_idx],
mode="lines",
name="Forecast",
line=dict(color="red", dash="dash"),
)
)
fig.update_layout(
title=f"Stitched Full Time-Series Forecast (Channel {channel_idx})",
xaxis_title="Time",
yaxis_title="Value",
legend=dict(font=dict(size=12)),
hovermode="x unified",
height=500,
width=1000,
)
# fig.show()
"""import os
from datetime import datetime
image_folder = "saved_plots"
os.makedirs(image_folder, exist_ok=True)
image_path = os.path.join(image_folder, f"{image_name}.png")
fig.write_image(image_path)
print(f"Plot saved to: {image_path}")"""
# -----------------------------------------
# LIST OUT FINAL ANOMALIES AND SAVE TO CSV
import numpy as np
channel_idx = 0
true_flat = stitched_true[channel_idx]
pred_flat = stitched_pred[channel_idx]
epsilon = 1e-6
relative_errors = ((true_flat - pred_flat) ** 2) / (np.abs(true_flat) + epsilon)
# Get indices of top 10 anomaly points (sorted descending)
top_10_indices = np.argsort(relative_errors)[-10:][::-1]
print("Top 10 anomaly indices:", top_10_indices.tolist())
L = anomaly_end - anomaly_start + 1
correct_anomalies = []
for index in top_10_indices:
if (
min(anomaly_start - 100, anomaly_start - L) < index
and max(anomaly_end + 100, anomaly_end + L) > index
):
correct_anomalies.append(index)
# Save to csv
import os
import pandas as pd
anomaly_folder = "saved_anomalies"
os.makedirs(anomaly_folder, exist_ok=True)
anomaly_file = os.path.join(anomaly_folder, "anomalies_log.csv")
df = pd.DataFrame([top_10_indices.tolist()])
df["correct_anomalies"] = [correct_anomalies]
if not os.path.exists(anomaly_file):
headers = [f"anomaly_{i + 1}" for i in range(10)] + ["correct_anomalies"]
df.to_csv(anomaly_file, index=False, header=headers)
else:
df.to_csv(anomaly_file, mode="a", index=False, header=False)
print(f"Anomalies saved to: {anomaly_file}")
# Clean up
del model
del train_dataset