The user wants a Python function for detecting anomalies using the Isolation Forest method from sklearn. They didn't specify a particular data format, so I’ll design a general function that can take in both training and new data to return anomaly scores or labels. I should keep the code concise but complete, with minimal explanation regarding parameters. I'll also provide example usage, possibly with pandas DataFrame. Let’s make sure it's helpful without being overly complicated! Here’s a simple, reusable Python function to detect anomalies using Isolation Forest:
python
from typing import Tuple
import numpy as np
from sklearn.ensemble import IsolationForest
def detect_anomalies_isolation_forest(
X: np.ndarray,
contamination: float = 0.01,
n_estimators: int = 100,
max_samples: str | int | float = "auto",
random_state: int | None = 42,
) -> Tuple[np.ndarray, np.ndarray, IsolationForest]:
"""
Detect anomalies in data using Isolation Forest.
Parameters
----------
X : np.ndarray
2D array-like of shape (n_samples, n_features).
Data on which to fit the model and detect anomalies.
contamination : float, default=0.01
The expected proportion of anomalies in the data (0 < contamination <= 0.5).
n_estimators : int, default=100
Number of base estimators (trees) in the Isolation Forest.
max_samples : {"auto"}, int or float, default="auto"
Number of samples to draw to train each base estimator.
- If int: draws `max_samples` samples.
- If float: draws `max_samples * n_samples` samples.
- If "auto": min(256, n_samples).
random_state : int or None, default=42
Random seed for reproducibility.
Returns
-------
labels : np.ndarray
Array of shape (n_samples,) with values:
- 1 for normal points
- -1 for anomalies
anomaly_scores : np.ndarray
Anomaly scores (the higher, the more anomalous).
model : IsolationForest
The fitted IsolationForest model (can be reused on new data).
"""
# Ensure numpy array
X = np.asarray(X)
# Create and fit the model
model = IsolationForest(
n_estimators=n_estimators,
max_samples=max_samples,
contamination=contamination,
random_state=random_state,
n_jobs=-1,
)
model.fit(X)
# Predict labels: 1 for normal, -1 for anomaly
labels = model.predict(X)
# IsolationForest.decision_function: higher -> more normal
# Convert to anomaly scores: higher -> more anomalous
anomaly_scores = -model.decision_function(X)
return labels, anomaly_scores, model
Minimal usage example
python
import numpy as np
# Toy data: mostly around (0,0), a few far away points as anomalies
normal_data = np.random.randn(100, 2)
anomalies = np.array([[8, 8], [9, 9], [-10, 10]])
X = np.vstack([normal_data, anomalies])
labels, scores, model = detect_anomalies_isolation_forest(
X,
contamination=0.03 # ~3 anomalies in 103 points
)
# Indices of detected anomalies
anomaly_indices = np.where(labels == -1)[0]
print("Anomaly indices:", anomaly_indices)
print("Anomaly scores:", scores[anomaly_indices])
If you tell me the format of your data (NumPy, pandas DataFrame, etc.) or your use case (time series, tabular, etc.), I can tailor this function further (e.g., with scaling, fitting on train set and detecting on test set).