rtik007's picture
Update app.py
e534cc9 verified
raw
history blame
3.28 kB
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons, make_blobs
import gradio as gr
# Function to generate interactive feature scatter plots
def plot_interactive_feature_scatter(input_data, feature_x, feature_y, n_samples):
# Generate data based on the selected dataset
if input_data == "Moons":
data, _ = make_moons(n_samples=n_samples, noise=0.05)
else:
data, _ = make_blobs(n_samples=n_samples, random_state=0)
# Simulate feature selection by indexing
x_data = data[:, 0] if feature_x == "Feature1" else data[:, 1]
y_data = data[:, 1] if feature_y == "Feature2" else data[:, 0]
# Generate scatter plot
plt.figure(figsize=(6, 6))
plt.scatter(x_data, y_data, alpha=0.8, c="blue", s=20, label="Features")
plt.title(f"Feature Interaction Scatter Plot - {feature_x} vs {feature_y}")
plt.xlabel(feature_x)
plt.ylabel(feature_y)
plt.legend()
return plt.gcf()
# Function for anomaly examples (Optional feature row)
def plot_anomaly_examples(input_data, n_samples, outliers_fraction):
n_outliers = int(outliers_fraction * n_samples)
rng = np.random.RandomState(42)
data, _ = make_blobs(n_samples=n_samples, random_state=0)
outliers = rng.uniform(low=-6, high=6, size=(n_outliers, 2))
plt.figure(figsize=(5, 5))
plt.scatter(data[:, 0], data[:, 1], alpha=0.8, c="blue", s=20, label="Inliers")
plt.scatter(outliers[:, 0], outliers[:, 1], alpha=0.8, c="red", s=20, label="Outliers")
plt.title("Anomaly Examples")
plt.legend()
return plt.gcf()
# Gradio Interface
with gr.Blocks() as demo:
gr.Markdown(f"## 🕵️‍♀️ Interactive Anomaly Detection and Feature Scatter Plot 🕵️‍♂️")
# Inputs for dataset selection and sample size
input_data = gr.Radio(
choices=["Central Blob", "Two Blobs", "Blob with Noise", "Moons", "Noise"],
value="Moons",
label="Dataset"
)
n_samples = gr.Slider(
minimum=100, maximum=500, step=25, value=300, label="Number of Samples"
)
# Row for Interactive Feature Scatter Plot
gr.Markdown("### Feature Interaction: Scatter Plot")
with gr.Row():
feature_x = gr.Dropdown(choices=["Feature1", "Feature2"], value="Feature1", label="Feature 1")
feature_y = gr.Dropdown(choices=["Feature1", "Feature2"], value="Feature2", label="Feature 2")
scatter_plot_button = gr.Button("Generate Scatter Plot")
scatter_plot = gr.Plot(label="Interactive Feature Scatter Plot")
scatter_plot_button.click(
fn=plot_interactive_feature_scatter,
inputs=[input_data, feature_x, feature_y, n_samples],
outputs=scatter_plot,
)
# Row for Anomaly Examples (Optional)
gr.Markdown("### Anomaly Examples")
with gr.Row():
outliers_fraction = gr.Slider(
minimum=0.01, maximum=0.99, step=0.01, value=0.2, label="Fraction of Outliers"
)
anomaly_plot_button = gr.Button("Generate Anomaly Examples")
anomaly_plot = gr.Plot(label="Anomaly Examples")
anomaly_plot_button.click(
fn=plot_anomaly_examples,
inputs=[input_data, n_samples, outliers_fraction],
outputs=anomaly_plot,
)
demo.launch(debug=True)