import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
from typing import Union, Tuple
def detect_anomalies(
data: Union[np.ndarray, pd.DataFrame],
contamination: float = 0.1,
scale_features: bool = True,
random_state: int = 42,
return_scores: bool = False
) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
"""
Detect anomalies in the input data using Isolation Forest algorithm.
Parameters:
-----------
data : Union[np.ndarray, pd.DataFrame]
Input data. If DataFrame, columns are features.
contamination : float, default=0.1
The proportion of outliers in the data set. Used to define the threshold.
scale_features : bool, default=True
Whether to standardize features before fitting the model.
random_state : int, default=42
Random state for reproducibility.
return_scores : bool, default=False
If True, return both anomaly labels and anomaly scores.
Returns:
--------
np.ndarray or Tuple[np.ndarray, np.ndarray]
- If return_scores=False: Array of shape (n_samples,) with -1 for anomalies and 1 for normal points.
- If return_scores=True: Tuple of (labels, scores), where scores are the anomaly scores
(lower scores indicate more anomalous points).
Example:
--------
>>> import numpy as np
>>> X = np.random.randn(100, 2)
>>> X[-5:] += 5 # Introduce anomalies
>>> labels = detect_anomalies(X)
>>> print(np.sum(labels == -1)) # Number of detected anomalies
"""
# Convert DataFrame to numpy if necessary
if isinstance(data, pd.DataFrame):
data = data.values
# Ensure data is numpy array and 2D
data = np.asarray(data)
if data.ndim != 2:
raise ValueError("Data must be 2D (samples x features).")
# Scale features if requested
if scale_features:
scaler = StandardScaler()
data_scaled = scaler.fit_transform(data)
else:
data_scaled = data
# Initialize and fit Isolation Forest
iso_forest = IsolationForest(
contamination=contamination,
random_state=random_state,
n_jobs=-1 # Use all available cores
)
iso_forest.fit(data_scaled)
# Predict labels (-1: anomaly, 1: normal)
labels = iso_forest.predict(data_scaled)
if return_scores:
scores = iso_forest.score_samples(data_scaled)
return labels, scores
else:
return labels
Usage Notes:
Anomaly Detection Logic: Isolation Forest isolates anomalies faster than normal points by randomly partitioning the data. Points with shorter path lengths are more likely anomalies.
Preprocessing: Feature scaling is enabled by default as Isolation Forest performs better with standardized data.
Tuning: Adjust contamination based on your expected outlier rate (e.g., 0.05 for 5% outliers).
Performance: Efficient for high-dimensional data; handles thousands of samples quickly.
Dependencies: Requires scikit-learn, numpy, and pandas (optional for DataFrame input).
This function is production-ready and fully self-contained! Test it with your dataset. 🕵️♂️