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_classification
|
| 4 |
+
from sklearn.ensemble import IsolationForest
|
| 5 |
+
from sklearn.metrics import roc_curve, auc
|
| 6 |
+
import shap
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
import gradio as gr
|
| 9 |
+
from sklearn import svm
|
| 10 |
+
from sklearn.covariance import EllipticEnvelope
|
| 11 |
+
from sklearn.neighbors import LocalOutlierFactor
|
| 12 |
+
from sklearn.linear_model import SGDOneClassSVM
|
| 13 |
+
from sklearn.kernel_approximation import Nystroem
|
| 14 |
+
from sklearn.pipeline import make_pipeline
|
| 15 |
+
import time
|
| 16 |
+
from functools import partial
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# Generate synthetic data with 20 features
|
| 20 |
+
np.random.seed(42)
|
| 21 |
+
X, _ = make_classification(
|
| 22 |
+
n_samples=500,
|
| 23 |
+
n_features=20,
|
| 24 |
+
n_informative=10,
|
| 25 |
+
n_redundant=5,
|
| 26 |
+
n_clusters_per_class=1,
|
| 27 |
+
random_state=42
|
| 28 |
+
)
|
| 29 |
+
outliers = np.random.uniform(low=-6, high=6, size=(50, 20)) # Add outliers
|
| 30 |
+
X = np.vstack([X, outliers])
|
| 31 |
+
|
| 32 |
+
# Convert to DataFrame
|
| 33 |
+
columns = [f"Feature{i+1}" for i in range(20)]
|
| 34 |
+
df = pd.DataFrame(X, columns=columns)
|
| 35 |
+
|
| 36 |
+
# Fit Isolation Forest
|
| 37 |
+
iso_forest = IsolationForest(
|
| 38 |
+
n_estimators=100,
|
| 39 |
+
max_samples=256,
|
| 40 |
+
contamination=0.1,
|
| 41 |
+
random_state=42
|
| 42 |
+
)
|
| 43 |
+
iso_forest.fit(df)
|
| 44 |
+
|
| 45 |
+
# Predict anomaly scores
|
| 46 |
+
anomaly_scores = iso_forest.decision_function(df) # Negative values indicate anomalies
|
| 47 |
+
anomaly_labels = iso_forest.predict(df) # -1 for anomaly, 1 for normal
|
| 48 |
+
|
| 49 |
+
# Add results to DataFrame
|
| 50 |
+
df["Anomaly_Score"] = anomaly_scores
|
| 51 |
+
df["Anomaly_Label"] = np.where(anomaly_labels == -1, "Anomaly", "Normal")
|
| 52 |
+
|
| 53 |
+
# Generate true labels (1 for anomaly, 0 for normal) for ROC curve
|
| 54 |
+
true_labels = np.where(df["Anomaly_Label"] == "Anomaly", 1, 0)
|
| 55 |
+
|
| 56 |
+
# SHAP Explainability
|
| 57 |
+
explainer = shap.Explainer(iso_forest, df[columns])
|
| 58 |
+
shap_values = explainer(df[columns])
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Functions for Anomaly Detection Algorithms tab
|
| 62 |
+
def train_models(input_data, outliers_fraction, n_samples, clf_name):
|
| 63 |
+
"""Train anomaly detection models and plot results."""
|
| 64 |
+
n_outliers = int(outliers_fraction * n_samples)
|
| 65 |
+
n_inliers = n_samples - n_outliers
|
| 66 |
+
blobs_params = dict(random_state=0, n_samples=n_inliers, n_features=2)
|
| 67 |
+
NAME_CLF_MAPPING = {
|
| 68 |
+
"Robust covariance": EllipticEnvelope(contamination=outliers_fraction),
|
| 69 |
+
"One-Class SVM": svm.OneClassSVM(nu=outliers_fraction, kernel="rbf", gamma=0.1),
|
| 70 |
+
"One-Class SVM (SGD)": make_pipeline(
|
| 71 |
+
Nystroem(gamma=0.1, random_state=42, n_components=150),
|
| 72 |
+
SGDOneClassSVM(
|
| 73 |
+
nu=outliers_fraction,
|
| 74 |
+
shuffle=True,
|
| 75 |
+
fit_intercept=True,
|
| 76 |
+
random_state=42,
|
| 77 |
+
tol=1e-6,
|
| 78 |
+
),
|
| 79 |
+
),
|
| 80 |
+
"Isolation Forest": IsolationForest(contamination=outliers_fraction, random_state=42),
|
| 81 |
+
"Local Outlier Factor": LocalOutlierFactor(n_neighbors=35, contamination=outliers_fraction),
|
| 82 |
+
}
|
| 83 |
+
DATA_MAPPING = {
|
| 84 |
+
"Central Blob": make_blobs(centers=[[0, 0], [0, 0]], cluster_std=0.5, **blobs_params)[0],
|
| 85 |
+
"Two Blobs": make_blobs(centers=[[2, 2], [-2, -2]], cluster_std=[0.5, 0.5], **blobs_params)[0],
|
| 86 |
+
"Blob with Noise": make_blobs(centers=[[2, 2], [-2, -2]], cluster_std=[1.5, 0.3], **blobs_params)[0],
|
| 87 |
+
"Moons": 4.0
|
| 88 |
+
* (make_moons(n_samples=n_samples, noise=0.05, random_state=0)[0] - np.array([0.5, 0.25])),
|
| 89 |
+
"Noise": 14.0 * (np.random.RandomState(42).rand(n_samples, 2) - 0.5),
|
| 90 |
+
}
|
| 91 |
+
xx, yy = np.meshgrid(np.linspace(-7, 7, 150), np.linspace(-7, 7, 150))
|
| 92 |
+
clf = NAME_CLF_MAPPING[clf_name]
|
| 93 |
+
plt.figure(figsize=(10, 8))
|
| 94 |
+
X = DATA_MAPPING[input_data]
|
| 95 |
+
rng = np.random.RandomState(42)
|
| 96 |
+
X = np.concatenate([X, rng.uniform(low=-6, high=6, size=(n_outliers, 2))], axis=0)
|
| 97 |
+
t0 = time.time()
|
| 98 |
+
clf.fit(X)
|
| 99 |
+
t1 = time.time()
|
| 100 |
+
|
| 101 |
+
if clf_name == "Local Outlier Factor":
|
| 102 |
+
y_pred = clf.fit_predict(X)
|
| 103 |
+
else:
|
| 104 |
+
y_pred = clf.fit(X).predict(X)
|
| 105 |
+
|
| 106 |
+
if clf_name != "Local Outlier Factor":
|
| 107 |
+
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
|
| 108 |
+
Z = Z.reshape(xx.shape)
|
| 109 |
+
plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors="black")
|
| 110 |
+
|
| 111 |
+
colors = np.array(["#377eb8", "#ff7f00"])
|
| 112 |
+
plt.scatter(X[:, 0], X[:, 1], s=30, color=colors[(y_pred + 1) // 2])
|
| 113 |
+
|
| 114 |
+
plt.xlim(-7, 7)
|
| 115 |
+
plt.ylim(-7, 7)
|
| 116 |
+
plt.xticks(())
|
| 117 |
+
plt.yticks(())
|
| 118 |
+
plt.title(f"{clf_name} (time: {t1 - t0:.2f}s)")
|
| 119 |
+
return plt
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# Create Gradio interface
|
| 123 |
+
with gr.Blocks() as demo:
|
| 124 |
+
gr.Markdown("# Isolation Forest Anomaly Detection")
|
| 125 |
+
|
| 126 |
+
with gr.Tab("Anomaly Detection Algorithms"):
|
| 127 |
+
gr.Markdown("## Compare Anomaly Detection Algorithms")
|
| 128 |
+
input_models = [
|
| 129 |
+
"Robust covariance", "One-Class SVM", "One-Class SVM (SGD)", "Isolation Forest", "Local Outlier Factor"
|
| 130 |
+
]
|
| 131 |
+
input_data = gr.Radio(
|
| 132 |
+
choices=["Central Blob", "Two Blobs", "Blob with Noise", "Moons", "Noise"],
|
| 133 |
+
value="Moons",
|
| 134 |
+
label="Dataset Type"
|
| 135 |
+
)
|
| 136 |
+
n_samples = gr.Slider(
|
| 137 |
+
minimum=100, maximum=500, step=25, value=300, label="Number of Samples"
|
| 138 |
+
)
|
| 139 |
+
outliers_fraction = gr.Slider(
|
| 140 |
+
minimum=0.1, maximum=0.9, step=0.1, value=0.2, label="Outlier Fraction"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
for clf_name in input_models:
|
| 144 |
+
plot = gr.Plot(label=clf_name)
|
| 145 |
+
fn = partial(train_models, clf_name=clf_name)
|
| 146 |
+
input_data.change(fn=fn, inputs=[input_data, outliers_fraction, n_samples], outputs=plot)
|
| 147 |
+
n_samples.change(fn=fn, inputs=[input_data, outliers_fraction, n_samples], outputs=plot)
|
| 148 |
+
outliers_fraction.change(fn=fn, inputs=[input_data, outliers_fraction, n_samples], outputs=plot)
|
| 149 |
+
|
| 150 |
+
# Launch the Gradio app
|
| 151 |
+
demo.launch()
|