Certainly! Below is a Python module that defines a Beta API for detailed distribution visualization using PyTorch (torch) and Plotly (plotly). This implementation adheres to PEP-8 standards, incorporates type hints using the typing module, and includes comprehensive error handling to ensure robustness. The code is optimized for performance and readability, making it suitable for handling large datasets and scalable applications.
Overview
The Beta class provides methods to:
- Initialize with a PyTorch tensor representing the data distribution.
- Generate Interactive Plots using Plotly, including histogram and kernel density estimates.
- Animate Distributions to visualize changes over time or different parameters (play/stop functionality).
- Provide Summary Statistics to aid in understanding the distribution in detail.
Code Implementation
import logging
from typing import Optional, Union, Tuple
import torch
import plotly.graph_objs as go
from plotly.subplots import make_subplots
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Beta:
"""
Beta API for detailed distribution visualization using PyTorch and Plotly.
"""
def __init__(self, data: torch.Tensor):
"""
Initialize the Beta visualization with a PyTorch tensor.
Args:
data (torch.Tensor): A 1D tensor containing distribution data.
Raises:
ValueError: If the input data is not a 1D tensor.
TypeError: If the input data is not a torch.Tensor.
"""
if not isinstance(data, torch.Tensor):
logger.error("Input data must be a torch.Tensor.")
raise TypeError("Input data must be a torch.Tensor.")
if data.dim() != 1:
logger.error("Input tensor must be 1-dimensional.")
raise ValueError("Input tensor must be 1-dimensional.")
self.data = data.cpu().numpy()
logger.info("Beta visualization initialized with data of shape %s.", self.data.shape)
def summary_statistics(self) -> dict:
"""
Compute summary statistics of the distribution.
Returns:
dict: A dictionary containing mean, median, std, min, and max.
"""
mean = float(torch.mean(torch.from_numpy(self.data)))
median = float(torch.median(torch.from_numpy(self.data)))
std = float(torch.std(torch.from_numpy(self.data)))
data_min = float(torch.min(torch.from_numpy(self.data)))
data_max = float(torch.max(torch.from_numpy(self.data)))
logger.info("Computed summary statistics.")
return {
"mean": mean,
"median": median,
"std": std,
"min": data_min,
"max": data_max,
}
def plot_histogram(self, bins: int = 30, title: str = "Histogram") -> go.Figure:
"""
Create a histogram of the distribution.
Args:
bins (int, optional): Number of bins for the histogram. Defaults to 30.
title (str, optional): Title of the plot. Defaults to "Histogram".
Returns:
go.Figure: A Plotly figure object representing the histogram.
"""
try:
histogram = go.Histogram(x=self.data, nbinsx=bins, name='Histogram')
layout = go.Layout(title=title, xaxis_title='Value', yaxis_title='Frequency')
fig = go.Figure(data=[histogram], layout=layout)
logger.info("Histogram plot created with %d bins.", bins)
return fig
except Exception as e:
logger.exception("Failed to create histogram plot: %s", e)
raise
def plot_kde(self, title: str = "Kernel Density Estimate") -> go.Figure:
"""
Create a Kernel Density Estimate (KDE) plot of the distribution.
Args:
title (str, optional): Title of the plot. Defaults to "Kernel Density Estimate".
Returns:
go.Figure: A Plotly figure object representing the KDE plot.
"""
try:
kde = go.Histogram(
x=self.data,
histnorm='probability density',
nbinsx=50,
name='KDE',
opacity=0.75
)
layout = go.Layout(title=title, xaxis_title='Value', yaxis_title='Density')
fig = go.Figure(data=[kde], layout=layout)
logger.info("KDE plot created.")
return fig
except Exception as e:
logger.exception("Failed to create KDE plot: %s", e)
raise
def animate_distributions(
self,
frames: int = 10,
title: str = "Animated Distribution",
mode: str = 'lines'
) -> go.Figure:
"""
Create an animated plot of the distribution, simulating changes over frames.
Args:
frames (int, optional): Number of frames in the animation. Defaults to 10.
title (str, optional): Title of the plot. Defaults to "Animated Distribution".
mode (str, optional): Mode for scatter plot (e.g., 'lines', 'markers'). Defaults to 'lines'.
Returns:
go.Figure: A Plotly figure object representing the animated plot.
"""
try:
fig = make_subplots()
data_frames = []
for i in range(frames):
# Simulate dynamic data for animation
noise = torch.randn_like(torch.from_numpy(self.data)) * (i / frames)
animated_data = self.data + noise.numpy()
trace = go.Scatter(
x=animated_data,
mode=mode,
name=f'Frame {i+1}'
)
data_frames.append(go.Frame(data=[trace], name=str(i)))
fig.add_trace(go.Scatter(x=self.data, y=[0]*len(self.data), mode=mode))
fig.update_layout(
title=title,
xaxis_title='Value',
yaxis_title='Density',
updatemenus=[
dict(
type='buttons',
buttons=[
dict(label="Play",
method="animate",
args=[None, {"frame": {"duration": 500, "redraw": True},
"fromcurrent": True}]),
dict(label="Pause",
method="animate",
args=[[None], {"frame": {"duration": 0, "redraw": False},
"mode": "immediate",
"transition": {"duration": 0}}])
],
showactive=False,
y=1,
x=1.05
)
]
)
fig.frames = data_frames
logger.info("Animated distribution plot created with %d frames.", frames)
return fig
except Exception as e:
logger.exception("Failed to create animated plot: %s", e)
raise
def plot_combined(self, bins: int = 30) -> go.Figure:
"""
Create a combined plot of histogram and KDE.
Args:
bins (int, optional): Number of bins for the histogram. Defaults to 30.
Returns:
go.Figure: A Plotly figure object with both histogram and KDE.
"""
try:
hist = go.Histogram(
x=self.data,
nbinsx=bins,
name='Histogram',
opacity=0.6
)
kde_trace = go.Histogram(
x=self.data,
histnorm='probability density',
nbinsx=50,
name='KDE',
opacity=0.6
)
layout = go.Layout(
title='Histogram and KDE',
xaxis_title='Value',
yaxis_title='Density',
barmode='overlay'
)
fig = go.Figure(data=[hist, kde_trace], layout=layout)
logger.info("Combined histogram and KDE plot created.")
return fig
except Exception as e:
logger.exception("Failed to create combined plot: %s", e)
raise
Usage Example
Below is an example of how to use the Beta class to visualize a distribution:
import torch
def main():
# Generate sample data
data = torch.randn(1000) # Normal distribution
# Initialize Beta visualization
beta_viz = Beta(data)
# Print summary statistics
stats = beta_viz.summary_statistics()
print("Summary Statistics:", stats)
# Plot histogram
hist_fig = beta_viz.plot_histogram(bins=50, title="Sample Histogram")
hist_fig.show()
# Plot KDE
kde_fig = beta_viz.plot_kde(title="Sample KDE")
kde_fig.show()
# Plot combined histogram and KDE
combined_fig = beta_viz.plot_combined(bins=50)
combined_fig.show()
# Animate distributions
animated_fig = beta_viz.animate_distributions(frames=20, title="Animated Distribution")
animated_fig.show()
if __name__ == "__main__":
main()
Explanation
-
Initialization (__init__):
- Validates that the input is a 1D
torch.Tensor.
- Converts the tensor to a NumPy array for compatibility with Plotly.
-
Summary Statistics (summary_statistics):
- Computes mean, median, standard deviation, minimum, and maximum.
- Returns these statistics in a dictionary.
-
Histogram Plot (plot_histogram):
- Creates a histogram using Plotly's
Histogram.
- Configurable number of bins and title.
-
KDE Plot (plot_kde):
- Approximates a KDE by normalizing the histogram to represent density.
- Configurable title.
-
Animated Distributions (animate_distributions):
- Simulates animation by adding noise to the data across frames.
- Provides play and pause buttons for interaction.
-
Combined Plot (plot_combined):
- Overlays histogram and KDE for comprehensive visualization.
- Uses semi-transparent histograms to visualize both distributions.
-
Error Handling:
- Each plotting method includes try-except blocks to catch and log exceptions.
- Raises exceptions after logging to notify the caller of issues.
-
Logging:
- Utilizes Python’s
logging module to log informational messages and errors.
- Helps in debugging and monitoring the API's behavior.
Dependencies
Ensure you have the necessary modules installed:
pip install torch plotly
Conclusion
The Beta API provides a comprehensive and interactive way to visualize and analyze distributions using PyTorch tensors and Plotly. By adhering to best practices in coding standards, type hinting, error handling, and optimization, this implementation ensures maintainability and scalability for various data visualization tasks.