DHEIVER's picture
Update app.py
aa4a0b3
raw
history blame
2.26 kB
import gradio as gr
import pandas as pd
import numpy as np
from statsmodels.tsa.seasonal import STL
from sklearn.ensemble import IsolationForest
import matplotlib.pyplot as plt
def detect_anomalies(series, seasonality_window=7, anomaly_threshold=0.05):
# Decompose series using Seasonal-Trend decomposition using LOESS (STL)
decomposition = STL(series, seasonal=seasonality_window).fit()
trend = decomposition.trend
seasonal = decomposition.seasonal
residual = decomposition.resid
# Combine trend and seasonal components to form detrended series
detrended_series = series - trend - seasonal
# Fit the Isolation Forest model to detect anomalies in the detrended series
model = IsolationForest(contamination=anomaly_threshold)
model.fit(detrended_series.values.reshape(-1, 1))
# Predict outliers in the detrended series
outlier_predictions = model.predict(detrended_series.values.reshape(-1, 1))
anomalies = detrended_series[outlier_predictions == -1]
return anomalies.index
def plot_anomalies(series, anomalies):
plt.figure(figsize=(12, 6))
plt.plot(series, label='Original Series')
plt.scatter(anomalies, series[anomalies], color='red', label='Anomalies')
plt.legend()
plt.title('Time Series with Anomalies')
plt.xlabel('Date')
plt.ylabel('Value')
plt.show()
# Função para o Gradio
def anomaly_detection_app(time_series_txt):
# Carregar a série temporal a partir do arquivo de texto
df = pd.read_csv(time_series_txt, header=None, names=["Date", "Value"])
df['Date'] = pd.to_datetime(df['Date'])
df = df.set_index('Date')
# Detectar anomalias na série temporal
anomalies = detect_anomalies(df['Value'])
# Plotar a série temporal com as anomalias destacadas
plot_anomalies(df['Value'], anomalies)
return anomalies
# Interface do Gradio
iface = gr.Interface(
fn=anomaly_detection_app,
inputs=gr.inputs.File(label="Carregar série temporal (TXT)"),
outputs="text",
title="Análise de Anomalias em Séries Temporais",
description="Este aplicativo detecta anomalias em uma série temporal carregada através de um arquivo de texto (TXT).",
live=True
)
if __name__ == "__main__":
iface.launch()