upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from huggingface_hub import from_pretrained_keras
|
3 |
+
import pandas as pd
|
4 |
+
import numpy as np
|
5 |
+
import json
|
6 |
+
|
7 |
+
f = open('scaler.json')
|
8 |
+
scaler = json.load(f)
|
9 |
+
|
10 |
+
def normalize_data(data):
|
11 |
+
df_test_value = (data - scaler["mean"]) / scaler["std"]
|
12 |
+
return df_test_value
|
13 |
+
|
14 |
+
def plot_test_data(df_test_value):
|
15 |
+
fig, ax = plt.subplots()
|
16 |
+
df_test_value.plot(legend=False, ax=ax)
|
17 |
+
return fig
|
18 |
+
|
19 |
+
def get_anomalies(df_test_value):
|
20 |
+
# Create sequences from test values.
|
21 |
+
x_test = create_sequences(df_test_value.values)
|
22 |
+
model = from_pretrained_keras("remeajayi/timeseries-anomaly-detection")
|
23 |
+
|
24 |
+
# Get test MAE loss.
|
25 |
+
x_test_pred = model.predict(x_test)
|
26 |
+
test_mae_loss = np.mean(np.abs(x_test_pred - x_test), axis=1)
|
27 |
+
test_mae_loss = test_mae_loss.reshape((-1))
|
28 |
+
|
29 |
+
# Detect all the samples which are anomalies.
|
30 |
+
anomalies = test_mae_loss > threshold
|
31 |
+
return anomalies
|
32 |
+
|
33 |
+
def plot_anomalies(df_test_value, data, anomalies):
|
34 |
+
# data i is an anomaly if samples [(i - timesteps + 1) to (i)] are anomalies
|
35 |
+
anomalous_data_indices = []
|
36 |
+
for data_idx in range(TIME_STEPS - 1, len(df_test_value) - TIME_STEPS + 1):
|
37 |
+
if np.all(anomalies[data_idx - TIME_STEPS + 1 : data_idx]):
|
38 |
+
anomalous_data_indices.append(data_idx)
|
39 |
+
df_subset = data.iloc[anomalous_data_indices]
|
40 |
+
fig, ax = plt.subplots()
|
41 |
+
data.plot(legend=False, ax=ax)
|
42 |
+
df_subset.plot(legend=False, ax=ax, color="r")
|
43 |
+
return fig
|
44 |
+
|
45 |
+
def master(file):
|
46 |
+
# read file
|
47 |
+
data = pd.read_csv(file, parse_dates=True, index_col="timestamp")
|
48 |
+
df_test_value = normalize_data(data)
|
49 |
+
# plot input test data
|
50 |
+
plot1 = plot_test_data(df_test_value)
|
51 |
+
# predict
|
52 |
+
anomalies = get_anomalies(df_test_value)
|
53 |
+
#plot anomalous data points
|
54 |
+
plot2 = plot_anomalies(df_test_value, data, anomalies)
|
55 |
+
return plot2
|
56 |
+
|
57 |
+
iface = gr.Interface(master,
|
58 |
+
gr.inputs.File(label="csv file"),
|
59 |
+
outputs=['plot'],
|
60 |
+
examples=["art_daily_jumpsup.csv"], title="Anomaly detection of timeseries data",
|
61 |
+
description = "Anomaly detection of timeseries data.",
|
62 |
+
article = "Author: <a href=\"https://www.linkedin.com/in/olohireme-ajayi/\">Reme Ajayi</a>"
|
63 |
+
)
|
64 |
+
|
65 |
+
|
66 |
+
iface.launch()
|