moons / app.py
DanOPT
Fixed typo
9f4bc50
Raw History Blame Contribute Delete
4.44 kB
import gradio as gr
import numpy as np
from sklearn.datasets import make_moons
import matplotlib.pyplot as plt
import tempfile
def generate_moons(n_samples, noise, random_state):
# Generate the moon dataset
X, y = make_moons(n_samples=n_samples, noise=noise, random_state=random_state)
# Plot the data
fig, ax = plt.subplots(figsize=(10, 8))
ax.scatter(X[y == 0, 0], X[y == 0, 1], color='blue', label='Moon 1')
ax.scatter(X[y == 1, 0], X[y == 1, 1], color='green', label='Moon 2')
ax.set_title("Moons Dataset")
ax.set_xlabel("Feature 1")
ax.set_ylabel("Feature 2")
ax.legend()
# Save the plot to a temporary file
temp_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
plt.savefig(temp_file.name)
plt.close()
# Merge data and labels
merged_data = np.column_stack((X, y)).tolist() # Combine data and labels into a single array
return temp_file.name, merged_data
# Define the Gradio interface
with gr.Blocks(title="Moons Dataset") as demo:
gr.Markdown("# Dataset Generator: Moons\n\n"
"This tool generates two interleaving half circles using scikit-learn's `make_moons()` function.\n"
"You can specify the number of samples, noise, and randomness.\n\n"
"The tool will visualize the dataset and provide the underlying Python code used to generate it.\n\n"
"## Parameters Description:\n"
"- **Number of Samples**: The number of data points in the result dataset.\n"
"- **Noise**: The standard deviation of the gaussian noise added to the data (default is 0.0).\n"
"- **Random State**: Seed for reproducible output (default is None).\n\n"
"For more information about the function sklearn.datasets.make_moons() visit: [https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_moons.html](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_moons.html).")
with gr.Row():
n_samples = gr.Slider(minimum=0, maximum=5000, value=1000, step=1, label="Samples")
noise = gr.Slider(minimum=0.0, maximum=1.0, value=0.1, step=0.01, label="Noise")
random_state = gr.Slider(minimum=0, maximum=100, value=0, step=1, label="Random State")
with gr.Row():
generate_btn = gr.Button("Generate")
with gr.Row():
output_image = gr.Image(label="Plot")
# Output code box
with gr.Row():
output_code = gr.Textbox(label="Python Code", lines=7, interactive=False)
# Data table
with gr.Row():
output_data = gr.Dataframe(label="Generated Data and Labels", headers=["Feature 1", "Feature 2", "Label"])
# Function to generate the original scikit-learn make_moons code
def generate_sklearn_code(n_samples, noise, random_state):
random_state_str = 'None' if random_state is None else random_state
code = (
f"from sklearn.datasets import make_moons\n\n"
f"# Generate moon dataset\n"
f"X, y = make_moons(\n"
f" n_samples={n_samples},\n"
f" noise={noise},\n"
f" random_state={random_state_str}\n"
f")"
)
return code
# Logic to handle input and call generate_moons
def handle_output(n_samples, noise, random_state):
# Input validation
if n_samples <= 0:
return "Error: Number of samples must be a positive integer.", None, ""
# Convert random_state to integer if provided
random_state = int(random_state) if random_state is not None else None
try:
# Generate moons dataset
image, merged_data = generate_moons(
n_samples=int(n_samples),
noise=float(noise),
random_state=random_state
)
# Generate the original make_moons function call
sklearn_code = generate_sklearn_code(n_samples, noise, random_state)
return image, merged_data, sklearn_code
except Exception as e:
return f"An error occurred: {str(e)}", None, ""
generate_btn.click(
fn=handle_output,
inputs=[n_samples, noise, random_state],
outputs=[output_image, output_data, output_code]
)
# Launch the app
demo.launch()