I'm focused on grasping the user's need for an anomaly detection script. Currently, I'm identifying the core components, starting with the data source. Next, I will determine the necessary data preprocessing steps.
Formulating the Implementation
I'm now outlining the steps for building the script. My focus is on library imports, specifically pandas, NumPy, Matplotlib, and Scikit-learn. I've decided to start with synthetic data—a sine wave with noise and outliers—to ensure immediate execution for the user. Data preparation involves reshaping the univariate time series into a suitable format for the Isolation Forest model.
Detailing Code Architecture
The focus is now on concrete implementation. I'm actively translating the plan into actual code snippets. I'm focusing on synthetic data, constructing the sine wave, adding noise, and incorporating outliers. Then, I'm adapting the data for the Isolation Forest model and adding relevant code comments. Finally, I will determine the best way to present the results, likely with matplotlib.
Developing the Code Structure
I'm presently focused on structuring the code to enhance readability and maintainability. I'm leaning towards an organized script, prioritizing clarity for the user. I'll include detailed comments for each section. I'm meticulously generating a synthetic dataset—a sine wave with noise and outliers—to enable immediate testing. Subsequently, I'm working on the data processing, model training, prediction, and visualization components, ensuring all is cohesive and well-documented.
Developing the Solution Outline
I'm presently solidifying the overall structure of the solution. I've focused on breaking down the user's request into actionable steps. The plan includes generating synthetic data for immediate testing, followed by the model instantiation, training, prediction, and final visualization, and I'll emphasize the contamination parameter. I'm also thinking about adding a caveat about the feature engineering.
Structuring the Output
I'm now consolidating the script's final form, ensuring copy-paste compatibility. I'm focusing on incorporating thorough explanations for parameters like contamination and n_estimators. I'll include prerequisites and an overview of how Isolation Forest works. I'm also preparing to comment on the potential for more advanced feature engineering, keeping the core script straightforward but informative.
Here is a complete, runnable Python script to detect anomalies in time-series data using the Isolation Forest algorithm from the scikit-learn library.
This script includes data generation, model training, prediction, and visualization.
Prerequisites
You will need to install the necessary libraries:
bash
pip install pandas numpy matplotlib scikit-learn
The Python Script
python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest
def generate_data(n=300):
"""
Generates a synthetic time series with a sine wave pattern,
random noise, and inserted anomalies.
"""
np.random.seed(42)
# Create a time range
time_steps = pd.date_range(start='2023-01-01', periods=n, freq='D')
# Generate base signal (Sine wave)
X = np.linspace(0, 10 * np.pi, n)
values = np.sin(X)
# Add random noise
noise = np.random.normal(0, 0.1, n)
values = values + noise
# Create DataFrame
df = pd.DataFrame({'timestamp': time_steps, 'value': values})
# artificially inject anomalies (spikes and drops)
# Anomaly 1: Huge spike
df.loc[50, 'value'] = 3.5
# Anomaly 2: Huge drop
df.loc[150, 'value'] = -3.0
# Anomaly 3: Cluster of anomalous behavior
df.loc[250:253, 'value'] = 2.0
return df
def train_isolation_forest(df, contamination=0.05):
"""
Trains the Isolation Forest model and predicts anomalies.
Parameters:
- contamination: The expected proportion of outliers in the dataset.
"""
# Isolation Forest expects a 2D array (n_samples, n_features)
data = df[['value']].values
# Initialize the model
# n_estimators: measure of ensemble size (number of trees)
# contamination: 'auto' or float. If float, it determines threshold for decision function.
model = IsolationForest(n_estimators=100,
contamination=contamination,
random_state=42)
# Fit the model
model.fit(data)
# Predict: 1 for inliers, -1 for outliers
df['anomaly_score'] = model.decision_function(data)
df['anomaly_label'] = model.predict(data)
return df
def plot_anomalies(df):
"""
Visualizes the time series and highlights the anomalies.
"""
plt.figure(figsize=(12, 6))
# Plot original data
plt.plot(df['timestamp'], df['value'], color='blue', label='Normal Data', alpha=0.6)
# Filter anomalies (label == -1)
anomalies = df[df['anomaly_label'] == -1]
# Plot anomalies
plt.scatter(anomalies['timestamp'], anomalies['value'], color='red', label='Anomaly', s=50, zorder=5)
plt.title('Time Series Anomaly Detection using Isolation Forest')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.grid(True, linestyle='--', alpha=0.5)
plt.show()
# --- Main Execution ---
if __name__ == "__main__":
# 1. Generate Data
print("Generating synthetic data...")
df = generate_data()
# 2. Run Detection
# We assume roughly 5% of the data might be anomalous
print("Running Isolation Forest...")
df_processed = train_isolation_forest(df, contamination=0.05)
# 3. View Results
n_anomalies = len(df_processed[df_processed['anomaly_label'] == -1])
print(f"Detected {n_anomalies} anomalies.")
print(df_processed[df_processed['anomaly_label'] == -1].head())
# 4. Visualize
plot_anomalies(df_processed)
Key Concepts in the Script
contamination: This is the most critical parameter in IsolationForest. It tells the model what percentage of the data you assume to be "anomalous."
If you set contamination=0.05 (5%), the model will force the top 5% most distinct data points to be labeled as anomalies.
If you don't know the percentage, you can set it to 'auto', but specific tuning usually yields better results.
decision_function: Isolation Forest calculates an anomaly score. The lower the score, the more abnormal the data point is.
Data Shape: The model expects a 2D array (e.g., [[value1], [value2], ...]). We use df[['value']].values to format the data correctly.
How to improve for Real-World Data
In this example, we only used the raw value. In complex time-series analysis (like stock prices or server metrics), using the raw value is often not enough. You should create features such as:
Rolling Moving Average: To detect deviations from a trend rather than just high absolute numbers.
Lag features: Comparison to the value 1 hour ago or 24 hours ago.
Volatility: Rolling standard deviation.
You can pass these extra columns into the model: model.fit(df[['value', 'rolling_mean', 'volatility']]).