Certainly! Below is a comprehensive Python script that leverages PyTorch's distribution modules to create an interactive interface using Gradio and Plotly. This interface allows users to select from a variety of distributions, input relevant parameters, and visualize the Probability Density Function (PDF) and Cumulative Distribution Function (CDF).
Overview
- Dependencies: The script uses
torch, gradio, plotly, and standard Python libraries.
- Distribution Mapping: A dictionary maps distribution names to their corresponding PyTorch distribution classes and defines the required parameters for each.
- Dynamic UI Generation: Based on the selected distribution, the interface dynamically generates input fields for the necessary parameters.
- Plot Generation: Upon receiving valid inputs, the script generates PDF and/or CDF plots using Plotly.
- Error Handling: Comprehensive error handling ensures that users receive meaningful error messages for invalid inputs.
Code Implementation
import torch
import gradio as gr
import plotly.graph_objs as go
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
class DistributionInfo:
"""
A class to hold information about each distribution.
"""
def __init__(
self,
cls: Callable[..., torch.distributions.Distribution],
parameters: Dict[str, Dict[str, Any]],
support: Optional[Tuple[float, float]] = None,
) -> None:
"""
Initializes the DistributionInfo.
Args:
cls: The PyTorch distribution class.
parameters: A dictionary mapping parameter names to their type and default value.
support: The support of the distribution as a tuple (min, max).
"""
self.cls = cls
self.parameters = parameters
self.support = support
# Mapping of distribution names to their corresponding torch.distributions classes and parameters
DISTRIBUTIONS: Dict[str, DistributionInfo] = {
"Bernoulli": DistributionInfo(
cls=torch.distributions.Bernoulli,
parameters={
"probs": {"type": "float", "default": 0.5},
},
support=(0, 1),
),
"Beta": DistributionInfo(
cls=torch.distributions.Beta,
parameters={
"concentration1": {"type": "float", "default": 1.0},
"concentration0": {"type": "float", "default": 1.0},
},
support=(0, 1),
),
"Binomial": DistributionInfo(
cls=torch.distributions.Binomial,
parameters={
"total_count": {"type": "int", "default": 10},
"probs": {"type": "float", "default": 0.5},
},
support=(0, None),
),
"Categorical": DistributionInfo(
cls=torch.distributions.Categorical,
parameters={
"probs": {"type": "list", "default": [0.25, 0.25, 0.25, 0.25]},
},
support=(0, None),
),
"Normal": DistributionInfo(
cls=torch.distributions.Normal,
parameters={
"loc": {"type": "float", "default": 0.0},
"scale": {"type": "float", "default": 1.0},
},
support=(-np.inf, np.inf),
),
# Add more distributions here following the same structure
# ...
}
def create_distribution(
distribution_name: str, params: Dict[str, Any]
) -> torch.distributions.Distribution:
"""
Creates a PyTorch distribution object based on the distribution name and parameters.
Args:
distribution_name: The name of the distribution.
params: A dictionary of parameters for the distribution.
Returns:
An instance of a PyTorch distribution.
Raises:
ValueError: If the distribution is not supported or parameters are invalid.
"""
if distribution_name not in DISTRIBUTIONS:
raise ValueError(f"Unsupported distribution: {distribution_name}")
dist_info = DISTRIBUTIONS[distribution_name]
try:
# Convert list parameters to torch tensors if necessary
for param, value in params.items():
if dist_info.parameters[param]["type"] == "list":
params[param] = torch.tensor(value, dtype=torch.float32)
distribution = dist_info.cls(**params)
except Exception as e:
raise ValueError(f"Error creating distribution: {e}")
return distribution
def generate_x_values(
support: Tuple[float, float], num_points: int = 1000
) -> torch.Tensor:
"""
Generates x values over the support of the distribution.
Args:
support: A tuple indicating the range (min, max).
num_points: Number of points to generate.
Returns:
A tensor of x values.
"""
min_val, max_val = support
if min_val == -np.inf:
min_val = -10
if max_val == np.inf:
max_val = 10
return torch.linspace(min_val, max_val, steps=num_points)
def plot_distribution(
distribution: torch.distributions.Distribution,
plot_pdf: bool,
plot_cdf: bool,
) -> Tuple[go.Figure, str]:
"""
Generates Plotly figures for PDF and/or CDF of the distribution.
Args:
distribution: The PyTorch distribution object.
plot_pdf: Whether to plot PDF.
plot_cdf: Whether to plot CDF.
Returns:
A tuple containing the Plotly figure and an error message if any.
"""
try:
# Determine support for x-axis
if hasattr(distribution, "support"):
support = distribution.support.lower_bound, distribution.support.upper_bound
else:
support = (-10, 10)
x = generate_x_values(support)
x_np = x.numpy()
fig = go.Figure()
if plot_pdf:
pdf_values = distribution.log_prob(x).exp().numpy()
fig.add_trace(
go.Scatter(
x=x_np,
y=pdf_values,
mode="lines",
name="PDF",
)
)
if plot_cdf:
cdf_values = distribution.cdf(x).numpy()
fig.add_trace(
go.Scatter(
x=x_np,
y=cdf_values,
mode="lines",
name="CDF",
)
)
fig.update_layout(
title="Distribution Plot",
xaxis_title="x",
yaxis_title="Probability",
template="plotly_white",
)
return fig, ""
except Exception as e:
return go.Figure(), f"Error generating plot: {e}"
def validate_and_parse_params(
distribution_name: str, inputs: Dict[str, Any]
) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
"""
Validates and parses the input parameters for the selected distribution.
Args:
distribution_name: The name of the distribution.
inputs: A dictionary of input parameters as strings.
Returns:
A tuple containing the parsed parameters dictionary and an error message if any.
"""
dist_info = DISTRIBUTIONS.get(distribution_name)
if not dist_info:
return None, f"Unsupported distribution: {distribution_name}"
parsed_params = {}
for param, prop in dist_info.parameters.items():
value = inputs.get(param)
try:
if prop["type"] == "float":
parsed_params[param] = float(value)
elif prop["type"] == "int":
parsed_params[param] = int(value)
elif prop["type"] == "list":
# Expecting a comma-separated string of numbers
parsed_params[param] = [float(x.strip()) for x in value.split(",")]
else:
parsed_params[param] = value
except ValueError:
return None, f"Invalid value for parameter '{param}': {value}"
return parsed_params, None
def get_parameter_components(
distribution_name: str,
) -> List[gr.components.Component]:
"""
Generates a list of Gradio input components based on the distribution's parameters.
Args:
distribution_name: The name of the distribution.
Returns:
A list of Gradio components corresponding to the distribution's parameters.
"""
dist_info = DISTRIBUTIONS.get(distribution_name)
if not dist_info:
return []
components = []
for param, prop in dist_info.parameters.items():
if prop["type"] == "float":
components.append(
gr.Number(
label=param,
value=prop["default"],
)
)
elif prop["type"] == "int":
components.append(
gr.Number(
label=param,
value=prop["default"],
precision=0,
)
)
elif prop["type"] == "list":
components.append(
gr.Textbox(
label=f"{param} (comma separated)",
value=",".join(map(str, prop["default"])),
)
)
else:
components.append(
gr.Textbox(
label=param,
value=str(prop["default"]),
)
)
return components
def update_parameters(distribution_name: str) -> List[gr.components.Component]:
"""
Updates the parameter input fields based on the selected distribution.
Args:
distribution_name: The name of the selected distribution.
Returns:
A list of updated Gradio components.
"""
return get_parameter_components(distribution_name)
def plot_function(
distribution_name: str,
plot_pdf: bool,
plot_cdf: bool,
**kwargs,
) -> Union[go.Figure, str]:
"""
The main function to create distribution and generate plots.
Args:
distribution_name: The name of the distribution.
plot_pdf: Whether to plot PDF.
plot_cdf: Whether to plot CDF.
**kwargs: The parameters for the distribution.
Returns:
A Plotly figure or an error message.
"""
try:
# Validate and parse parameters
params, error = validate_and_parse_params(distribution_name, kwargs)
if error:
return error
# Create distribution
distribution = create_distribution(distribution_name, params)
# Generate plot
fig, plot_error = plot_distribution(distribution, plot_pdf, plot_cdf)
if plot_error:
return plot_error
return fig
except Exception as e:
return f"An error occurred: {e}"
def main() -> None:
"""
Sets up and launches the Gradio interface.
"""
with gr.Blocks() as demo:
gr.Markdown("# PyTorch Distributions Explorer")
gr.Markdown(
"Select a distribution, provide its parameters, and visualize its PDF and CDF."
)
with gr.Row():
distribution = gr.Dropdown(
choices=list(DISTRIBUTIONS.keys()),
value="Normal",
label="Distribution",
)
plot_pdf = gr.Checkbox(
label="Plot PDF", value=True
)
plot_cdf = gr.Checkbox(
label="Plot CDF", value=True
)
with gr.Row():
parameter_inputs = gr.Column()
with gr.Row():
plot_output = gr.Plot(label="Distribution Plot")
def on_distribution_change(name: str):
return update_parameters(name)
distribution.change(
on_distribution_change,
inputs=distribution,
outputs=parameter_inputs,
)
# Initialize parameter inputs
parameter_components = get_parameter_components(distribution.value)
parameter_inputs.render = lambda: parameter_components
for component in parameter_components:
parameter_inputs.add(component)
# Define the submit button
submit = gr.Button("Generate Plot")
# Define inputs for the plot_function
def gather_inputs(*args):
params = {}
for arg in args:
# The order of args corresponds to parameter_components
if isinstance(arg, list):
params[arg[0]] = arg[1]
else:
pass
return params
submit.click(
fn=plot_function,
inputs=[distribution, plot_pdf, plot_cdf] + parameter_components,
outputs=plot_output,
)
demo.launch()
if __name__ == "__main__":
main()
Explanation
-
DistributionInfo Class: This class encapsulates information about each distribution, including its PyTorch class, required parameters, and support range.
-
DISTRIBUTIONS Dictionary: Maps each distribution name to its corresponding DistributionInfo. For brevity, only a subset of distributions is included, but you can extend this dictionary by following the existing structure.
-
create_distribution Function: Instantiates a PyTorch distribution based on the selected name and user-provided parameters. It includes error handling to catch any issues during instantiation.
-
generate_x_values Function: Generates a range of x-values over which the PDF and CDF will be plotted. It intelligently handles infinite supports by limiting the range.
-
plot_distribution Function: Uses Plotly to create interactive plots for the PDF and CDF. It handles exceptions and returns appropriate error messages if plotting fails.
-
validate_and_parse_params Function: Ensures that user inputs are of the correct type and format. It converts input strings to the required data types, handling lists and numerical values appropriately.
-
get_parameter_components and update_parameters Functions: Dynamically generate Gradio input components based on the selected distribution's parameters. This enables the interface to adjust the input fields in real-time as different distributions are selected.
-
plot_function Function: The core function that orchestrates parameter validation, distribution creation, and plot generation. It serves as the callback for the Gradio interface.
-
main Function: Sets up the Gradio Blocks interface, defining the layout and interactive components. It initializes the interface with default values and establishes event handlers to manage user interactions.
-
Error Handling: Throughout the script, try-except blocks catch and relay errors to the user, ensuring robustness and a smooth user experience.
Extending the Script
To add more distributions:
-
Add to DISTRIBUTIONS: Extend the DISTRIBUTIONS dictionary with new entries following the existing pattern. Specify the PyTorch distribution class and define all required parameters with their types and default values.
-
Parameter Validation: Ensure that any new parameters are correctly parsed and validated in the validate_and_parse_params function.
-
UI Components: The dynamic generation of input fields will automatically handle new distributions based on the DISTRIBUTIONS mapping.
Running the Script
-
Install Dependencies:
pip install torch gradio plotly
-
Execute the Script:
python script_name.py
-
Interact with the Interface: A local Gradio interface will launch in your web browser, allowing you to explore various distributions.
Conclusion
This script provides a scalable and maintainable framework for exploring PyTorch distributions interactively. By adhering to PEP-8 standards, utilizing type hints, and implementing robust error handling, the code ensures clarity and reliability. You can further enhance this tool by adding more distributions, incorporating additional visualization features, or integrating other PyTorch functionalities as needed.