We need to write a Python script to detect anomalies in time-series data using Isolation Forest. The user likely wants a functional script that reads time-series data, applies Isolation Forest, and outputs anomalies. But we need to consider details: The data might be in CSV format with timestamps and values. The script should be self-contained, handle missing values, perhaps visualize or output anomaly flags.
We should produce a Python script that:
Imports necessary libraries: pandas, numpy, sklearn.ensemble.IsolationForest, maybe matplotlib for plotting.
Reads data from a file (maybe specified as command-line argument or hardcoded).
Preprocess: ensure time index, handle missing values (maybe interpolation or drop).
Feature engineering: For time series, Isolation Forest typically uses features like value, maybe lagged values, moving averages, etc. But the simplest is to use the raw value(s) as features. However, for univariate time series, we need to consider that Isolation Forest expects multidimensional features. We can create a feature matrix with sliding window (e.g., window size = 3) to capture temporal dependencies. Or we can simply use the value as a single feature, but then anomalies are just outliers in the value distribution, not necessarily temporal anomalies. But Isolation Forest can still work with a single feature; it will detect points that are far from the majority. However, for time series, it's common to use multiple features like lagged values to capture local patterns. We need to decide.
The user didn't specify the complexity; maybe just a straightforward script that reads a CSV with 'value' column and timestamps, then uses Isolation Forest on the 'value' column (maybe also include time as feature? Usually not directly). But we should provide a robust script that can be adapted.
Let's propose: The script reads a CSV file with columns 'timestamp' and 'value'. It sets timestamp as index. It then creates a sliding window of size n (e.g., 3) to include previous values as features. It then fits IsolationForest, predicts anomalies (anomaly = -1), and adds a column to the original DataFrame. It outputs the anomalies and optionally plots.
We can also include command-line argument parsing with argparse for flexibility: input file, output file, contamination (expected proportion of anomalies), window size, etc.
We should write a script that can be executed from the command line.
We need to handle missing values: if any NaN after window creation, we can drop those rows.
We also need to handle normalization? Isolation Forest does not require scaling, but it's based on random splits, so scaling doesn't matter much. But if we have multiple features with different scales, it might affect but still okay.
Let's design:
code
#!/usr/bin/env python3
import argparse
import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
def create_features(data, window_size):
# data is a Series of values
df = pd.DataFrame()
df['value'] = data
for i in range(1, window_size+1):
df[f'lag_{i}'] = data.shift(i)
# Also could include rolling statistics
df['rolling_mean'] = data.rolling(window=window_size).mean()
df['rolling_std'] = data.rolling(window=window_size).std()
return df.dropna()
def main():
parser = argparse.ArgumentParser(description='Detect anomalies in time-series using Isolation Forest.')
parser.add_argument('input_file', help='Path to input CSV file with timestamp and value columns.')
parser.add_argument('--output', '-o', help='Path to output CSV file with anomaly flags. If not provided, print to stdout.')
parser.add_argument('--timestamp_col', default='timestamp', help='Name of timestamp column.')
parser.add_argument('--value_col', default='value', help='Name of value column.')
parser.add_argument('--window', type=int, default=5, help='Window size for feature engineering.')
parser.add_argument('--contamination', type=float, default=0.01, help='Expected proportion of anomalies.')
parser.add_argument('--n_estimators', type=int, default=100, help='Number of trees in Isolation Forest.')
parser.add_argument('--random_state', type=int, default=42, help='Random seed for reproducibility.')
parser.add_argument('--plot', action='store_true', help='Show a plot of the time series with anomalies highlighted.')
args = parser.parse_args()
# Read data
df = pd.read_csv(args.input_file)
# Ensure timestamp column exists
if args.timestamp_col not in df.columns:
raise ValueError(f"Timestamp column '{args.timestamp_col}' not found.")
if args.value_col not in df.columns:
raise ValueError(f"Value column '{args.value_col}' not found.")
# Convert timestamp to datetime
df[args.timestamp_col] = pd.to_datetime(df[args.timestamp_col])
df = df.set_index(args.timestamp_col).sort_index()
# Create features
features_df = create_features(df[args.value_col], args.window)
# Standardize features (optional but recommended for algorithms using distance)
scaler = StandardScaler()
X = scaler.fit_transform(features_df.values)
# Fit Isolation Forest
clf = IsolationForest(n_estimators=args.n_estimators, contamination=args.contamination, random_state=args.random_state)
clf.fit(X)
# Predict: -1 for anomalies, 1 for normal
features_df['anomaly'] = clf.predict(X)
# Convert to boolean: True if anomaly (-1)
features_df['anomaly'] = features_df['anomaly'].apply(lambda x: x == -1)
# Merge with original data (only rows that have features)
result_df = df.join(features_df['anomaly'], how='left')
# Fill NaNs in anomaly as False (since those points didn't have enough window)
result_df['anomaly'] = result_df['anomaly'].fillna(False)
# Output
if args.output:
result_df.to_csv(args.output, index=True)
print(f"Results saved to {args.output}")
else:
print(result_df.to_csv(index=True))
if args.plot:
plt.figure(figsize=(12,6))
plt.plot(result_df.index, result_df[args.value_col], label='Value')
anomalies = result_df[result_df['anomaly']]
plt.scatter(anomalies.index, anomalies[args.value_col], color='red', label='Anomaly')
plt.xlabel('Time')
plt.ylabel('Value')
plt.title('Time Series with Anomalies')
plt.legend()
plt.show()
if __name__ == '__main__':
main()
That's a solid script. But we must ensure it runs: imports, etc.
We can also add a note about using sklearn.ensemble.IsolationForest. Provide docstring.
But maybe the user expects a simpler script without command-line arguments. However, we should provide a flexible solution.
Also, we need to consider that Isolation Forest works best with multiple features; our feature engineering includes lagged values and rolling stats, which helps.
We could also add an option to disable feature engineering and just use raw value (if window=0 maybe). But we can just set window size to 0? In the code, if window=0, we'd have no lag features, and rolling statistics would be of size 0? Better to handle: if window < 1, then just use the raw value, maybe create a 2D array. But let's keep it simple: assume window >= 1.
Alternatively, we can provide a simpler script that just takes value and fits Isolation Forest. However, time series anomalies often involve contextual anomalies, not just point outliers. Using lag features captures temporal context.
We'll present the script as above, with comments.
Now, for the final answer: we need to "Write a Python script to detect anomalies in time-series data using Isolation Forest." So we should output the code and maybe brief explanation.
Since it's a ChatGPT answer, we can provide the script in a code block and some explanation.
We must ensure it's correct and runs. Check: create_features function uses data.shift(i) for i from 1 to window inclusive? The code says for i in range(1, window_size+1): That gives lag_1 to lag_window. Then we also compute rolling_mean and rolling_std with window_size. That's fine. But note: after adding lags, the rolling stats will be computed on the original data, not the shifted, but that's okay. The rolling stats will also be NaN for first window_size points. Then dropna() will drop rows where any column is NaN. That means we lose the first window_size rows because of lag and rolling stats? Actually, lag_1 to lag_window will have NaN for first window rows? Let's compute: For i from 1 to window, shift(i) introduces i NaNs at the start. So the first window rows will have at least one NaN. Rolling stats also require window_size points, so first window_size-1 rows have NaN for rolling stats? Actually rolling(window_size) requires at least window_size points, so first window_size-1 rows are NaN. So overall, we lose about window rows. That's fine.
Then we scale, fit, predict. Then we join anomaly column to original df. The join will align by index (timestamp). Since features_df has index same as original but missing first rows, the join will have NaN for those missing rows; we fill with False. So anomalies flagged only for points that have enough context. That's acceptable.
We could also add a flag to include those initial points as not anomalies (False). That's fine.
Now, consider that Isolation Forest's contamination parameter expects proportion of anomalies; default 0.01. That is okay.
We might want to add an option to set the contamination to 'auto'? In sklearn, contamination can be 'auto' but we keep float.
We could also add a check: if contamination > 0.5, warn.
Now, ensure the script runs: We need to import StandardScaler; we did.
We should also consider that some users might not have matplotlib installed; we import but only use if plot flag; but we should either import conditionally or let it fail if plot=True but not installed. Could add try/except but not needed.
Better to import matplotlib.pyplot as plt only if needed? But we import at top; if not installed, script will fail even if plot not used. We can lazy import: inside the if args.plot block, import matplotlib.pyplot as plt. That's better. So we can remove the top import and import inside.
We'll adjust.
Also, we might want to add a --no-plot flag? We have --plot action store_true, so by default no plot.
We can also add a --verbose flag.
But okay.
Let's produce final answer with code and explanation.
We need to write the answer as a ChatGPT response: provide the script and maybe instructions on how to run it.
I'll produce a clean version.
One more thought: The script assumes CSV with headers. It would be good to have a check for missing values in the original data: we could drop NaNs before feature creation. We'll add:
df = df.dropna(subset=[args.value_col])
Now, finalize.
Also, we need to ensure the timestamp column is parsed correctly. Use pd.to_datetime.
Add an optional parameter for date format? Not needed.
Now, I'll write the answer.
We'll include:
Brief description of Isolation Forest.
How to use the script.
The code.
Make it self-contained.
Now, produce final output.
Below is a Python script that detects anomalies in time‑series data using the Isolation Forest algorithm.
It reads a CSV file containing a timestamp column and a value column, engineers temporal features (lagged values and rolling statistics), fits an Isolation Forest model, flags anomalies, and optionally saves the results or shows a plot.
python
How to Run
Save the script as anomaly_detector.py.
Ensure your data is in a CSV file with at least a timestamp column and a value column (e.g., timestamp, value).
Install the required packages if not already installed:
code
pip install pandas numpy scikit-learn matplotlib
Run the script:
code
python anomaly_detector.py data.csv --plot
Use --help to see all available options.
Key Features
Temporal Feature Engineering: Uses a sliding window to create lagged values and rolling statistics, allowing the model to capture local patterns.
Standardization: Features are scaled to zero mean and unit variance before feeding to the Isolation Forest.
Flexible Output: Results can be saved to a CSV or printed to stdout.
Visualization: The --plot flag shows the time series with anomalies highlighted in red.
Feel free to adjust parameters (e.g., --window, --contamination) to suit your dataset.
#!/usr/bin/env python3
"""
Anomaly detection in time‑series data using Isolation Forest.
Usage:
python anomaly_detector.py input.csv [options]
Options:
--output, -o Path to output CSV file (default: print to stdout)
--timestamp_col Name of the timestamp column (default: 'timestamp')
--value_col Name of the value column (default: 'value')
--window Window size for feature engineering (default: 5)
--contamination Expected proportion of anomalies (default: 0.01)
--n_estimators Number of trees in Isolation Forest (default: 100)
--random_state Random seed for reproducibility (default: 42)
--plot Show a plot of the time series with anomalies highlighted
"""
import argparse
import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
def create_features(data, window_size):
"""
Create a feature DataFrame with lagged values and rolling statistics.
"""
df = pd.DataFrame()
df['value'] = data
# Lagged values
for i in range(1, window_size + 1):
df[f'lag_{i}'] = data.shift(i)
# Rolling statistics
df['rolling_mean'] = data.rolling(window=window_size).mean()
df['rolling_std'] = data.rolling(window=window_size).std()
return df.dropna()
def main():
parser = argparse.ArgumentParser(description='Detect anomalies in time-series using Isolation Forest.')
parser.add_argument('input_file', help='Path to input CSV file with timestamp and value columns.')
parser.add_argument('--output', '-o', help='Path to output CSV file with anomaly flags. If not provided, print to stdout.')
parser.add_argument('--timestamp_col', default='timestamp', help='Name of timestamp column.')
parser.add_argument('--value_col', default='value', help='Name of value column.')
parser.add_argument('--window', type=int, default=5, help='Window size for feature engineering.')
parser.add_argument('--contamination', type=float, default=0.01, help='Expected proportion of anomalies.')
parser.add_argument('--n_estimators', type=int, default=100, help='Number of trees in Isolation Forest.')
parser.add_argument('--random_state', type=int, default=42, help='Random seed for reproducibility.')
parser.add_argument('--plot', action='store_true', help='Show a plot of the time series with anomalies highlighted.')
args = parser.parse_args()
# ------------------------------------------------------------------
# 1. Load and prepare data
# ------------------------------------------------------------------
df = pd.read_csv(args.input_file)
# Ensure required columns exist
if args.timestamp_col not in df.columns:
raise ValueError(f"Timestamp column '{args.timestamp_col}' not found.")
if args.value_col not in df.columns:
raise ValueError(f"Value column '{args.value_col}' not found.")
# Convert timestamp to datetime and set as index
df[args.timestamp_col] = pd.to_datetime(df[args.timestamp_col])
df = df.set_index(args.timestamp_col).sort_index()
# Drop rows with missing values in the target column
df = df.dropna(subset=[args.value_col])
# ------------------------------------------------------------------
# 2. Feature engineering
# ------------------------------------------------------------------
features = create_features(df[args.value_col], args.window)
# Standardize features (Isolation Forest does not strictly require it,
# but scaling makes splits more balanced when features have different ranges)
scaler = StandardScaler()
X = scaler.fit_transform(features.values)
# ------------------------------------------------------------------
# 3. Anomaly detection with Isolation Forest
# ------------------------------------------------------------------
clf = IsolationForest(
n_estimators=args.n_estimators,
contamination=args.contamination,
random_state=args.random_state
)
clf.fit(X)
# -1 = anomaly, 1 = normal
features['anomaly'] = clf.predict(X)
features['anomaly'] = features['anomaly'] == -1 # convert to boolean
# ------------------------------------------------------------------
# 4. Merge results back to original time series
# ------------------------------------------------------------------
# The first few rows were dropped during feature creation (NaNs)
result = df.join(features['anomaly'], how='left')
result['anomaly'] = result['anomaly'].fillna(False) # treat missing as normal
# ------------------------------------------------------------------
# 5. Output
# ------------------------------------------------------------------
if args.output:
result.to_csv(args.output, index=True)
print(f"Results saved to {args.output}")
else:
print(result.to_csv(index=True))
# ------------------------------------------------------------------
# 6. Optional plot
# ------------------------------------------------------------------
if args.plot:
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 6))
plt.plot(result.index, result[args.value_col], label='Value')
anomalies = result[result['anomaly']]
plt.scatter(anomalies.index, anomalies[args.value_col], color='red', label='Anomaly')
plt.xlabel('Time')
plt.ylabel('Value')
plt.title('Time Series with Anomalies')
plt.legend()
plt.show()
if __name__ == '__main__':
main()