The user wants a Python script for detecting anomalies in time-series data using Isolation Forest. I'll include libraries like pandas, numpy, and sklearn's IsolationForest. First, I'll address pre-processing steps, like creating rolling window features and processing time features. Although Isolation Forest is unsupervised, I could use one-dimensional time series with a windowed representation. The script will load a CSV file with timestamp and value columns, create features, fit the model, compute scores, and visualize the anomalies. I'll ensure the code is well-commented for clarity.Creating a sample dataset and script
I should provide a way for the user to simulate a dataset if they don’t provide a file or file path. The script should expect a 'data.csv' with 'timestamp' and 'value' columns, but I can also create synthetic data if needed.
I'll include an explanation and then provide the full script that detects anomalies using Isolation Forest. I'll keep it simple, without a command line interface, but allow optional input parameters. Lastly, I'll ensure comments guide the user on how to set everything up.Building a 1D time-series anomaly detection script
For a 1D time series, I’ll likely implement a sliding window approach or use the last 'n' values for each sample. I plan to calculate rolling mean and standard deviation, and then prepare these features for the Isolation Forest model.
I'll ensure the script is straightforward, keeping explanations minimal since the user requested only Python code. I'll also mention the contamination parameter, highlight anomalies in plots, and include instructions for installing necessary libraries without diving into too much detail.Writing a simple script with synthetic data option
Since the user hasn't provided any images, I'll focus on creating a Python script using text. I think it would be helpful to include a function to generate synthetic data for demonstration purposes. However, given they likely want to use their own data, I'll set it up to read from 'time_series.csv' in the same directory.
If that file doesn’t exist, the script will generate synthetic data. I want to keep the design simple without over-engineering, so I’ll avoid a complex command line interface and stick with a straightforward implementation.Finalizing the anomaly detection script
I think it’s best to create a straightforward script where the user can adapt the file path as needed. I'll outline the script, starting with loading the data from "time_series.csv". The script will create rolling mean and standard deviation features and then fit the Isolation Forest model.
I'll include sections to plot anomalies and save the results to a new CSV file. Additionally, I’ll incorporate a main function and a docstring while highlighting options, like customizing the contamination parameter, which indicates the expected fraction of anomalies. Scaling features is optional since the Isolation Forest handles that well. ```python
#!/usr/bin/env python3
"""
Detect anomalies in time-series data using Isolation Forest.
Assumed input CSV format (change as needed):
time_series.csv with columns:
- timestamp : datetime-like (e.g. "2023-01-01 00:00:00")
- value : numeric time-series value
Output:
- time_series_with_anomalies.csv (original data + anomaly labels/scores)
- anomaly_plot.png (plot with anomalies highlighted)
"""
import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest
import matplotlib.pyplot as plt
-----------------------------
Configuration
-----------------------------
INPUT_CSV = "time_series.csv" # path to your input file
TIMESTAMP_COL = "timestamp" # name of timestamp column
VALUE_COL = "value" # name of value column
ROLLING_WINDOW = 24 # window size for rolling stats (in number of points)
CONTAMINATION = 0.01 # expected fraction of anomalies (e.g. 1%)
RANDOM_STATE = 42 # for reproducibility
def load_time_series(path: str) -> pd.DataFrame:
"""Load and sort time-series data from CSV."""
df = pd.read_csv(path)
df[TIMESTAMP_COL] = pd.to_datetime(df[TIMESTAMP_COL])
df = df.sort_values(TIMESTAMP_COL).reset_index(drop=True)
return df
def create_features(df: pd.DataFrame, window: int) -> pd.DataFrame:
"""
Create features for Isolation Forest from a univariate time series.
code
Here we use:
- raw value
- rolling mean
- rolling standard deviation
- rolling min
- rolling max
"""
df = df.copy()
df["rolling_mean"] = df[VALUE_COL].rolling(window, min_periods=1).mean()
df["rolling_std"] = df[VALUE_COL].rolling(window, min_periods=1).std().fillna(0)
df["rolling_min"] = df[VALUE_COL].rolling(window, min_periods=1).min()
df["rolling_max"] = df[VALUE_COL].rolling(window, min_periods=1).max()
return df
def detect_anomalies(df: pd.DataFrame, contamination: float, random_state: int) -> pd.DataFrame:
"""Fit Isolation Forest and add anomaly labels and scores to the DataFrame."""
feature_cols = ["value", "rolling_mean", "rolling_std", "rolling_min", "rolling_max"]
X = df[feature_cols].values
code
model = IsolationForest(
n_estimators=200,
contamination=contamination,
random_state=random_state,
n_jobs=-1,
)
model.fit(X)
# decision_function: higher = more normal, lower = more abnormal
scores = model.decision_function(X)
# Convert so that higher values mean "more anomalous"
anomaly_score = -scores
labels = model.predict(X) # 1 = normal, -1 = anomaly
df["anomaly_score"] = anomaly_score
df["anomaly_label"] = (labels == -1).astype(int) # 1 = anomaly, 0 = normal
return df