This code trains an Isolation Forest on normal data and tests it on new points including clear anomalies. It prints which points are normal or anomalies.
import numpy as np
from sklearn.ensemble import IsolationForest
# Create sample data: mostly normal points around 0, some anomalies far away
np.random.seed(42)
X_train = np.random.randn(100, 2)
X_test = np.vstack([np.random.randn(20, 2), np.array([[10, 10], [15, 15]])])
# Train Isolation Forest
model = IsolationForest(contamination=0.1, random_state=42)
model.fit(X_train)
# Predict anomalies
predictions = model.predict(X_test)
# Print results
for i, pred in enumerate(predictions):
label = 'Anomaly' if pred == -1 else 'Normal'
print(f'Point {i}: {X_test[i]} is {label}')