Introduction
Anomaly detection helps find things that are different or unusual in data. It is useful to spot problems or rare events early.
from sklearn.ensemble import IsolationForest model = IsolationForest(contamination=0.1) model.fit(data) predictions = model.predict(new_data)
from sklearn.ensemble import IsolationForest model = IsolationForest(contamination=0.05) model.fit(X_train) preds = model.predict(X_test)
from sklearn.svm import OneClassSVM model = OneClassSVM(nu=0.1, kernel='rbf') model.fit(X_train) preds = model.predict(X_test)
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}')
print(predictions)?
from sklearn.ensemble import IsolationForest import numpy as np X_train = np.array([[1], [2], [3], [4], [5]]) model = IsolationForest(random_state=42) model.fit(X_train) X_test = np.array([[1], [10], [3]]) predictions = model.predict(X_test) print(predictions)
from sklearn.ensemble import IsolationForest model = IsolationForest() model.predict([[1], [2], [3]])
Pass the test and this pattern moves unknown