"""Visualization of datasets using Plotly with a focus on generalized, reusable code."""
from typing import Optional, List
import logging
import pandas as pd
from datasets import load_dataset, DatasetDict, Dataset
import plotly.express as px
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def visualize_dataset(dataset_name: str, config_name: Optional[str] = None, split_name: Optional[str] = None) -> None:
"""
Load a dataset by name and generate insightful visualizations using Plotly.
Parameters:
dataset_name (str): The name or path of the dataset to load.
config_name (Optional[str]): The configuration name of the dataset, if applicable.
split_name (Optional[str]): The split of the dataset to use, defaults to 'train' or the first available split.
"""
try:
# Load the dataset
dataset_dict: DatasetDict = load_dataset(dataset_name, name=config_name)
logger.info(f"Loaded dataset: {dataset_name}")
# Determine which split to use
if split_name and split_name in dataset_dict:
dataset: Dataset = dataset_dict[split_name]
logger.info(f"Using specified split: {split_name}")
elif 'train' in dataset_dict:
dataset = dataset_dict['train']
logger.info("Using 'train' split")
else:
# Use the first available split as a fallback
first_split: str = list(dataset_dict.keys())[0]
dataset = dataset_dict[first_split]
logger.warning(f"'train' split not found. Using first available split: {first_split}")
# Convert to a pandas DataFrame
df: pd.DataFrame = dataset.to_pandas()
logger.info("Converted dataset to pandas DataFrame")
# Identify numeric and categorical columns
numeric_columns: List[str] = df.select_dtypes(include='number').columns.tolist()
categorical_columns: List[str] = df.select_dtypes(include='object').columns.tolist()
logger.info(f"Numeric columns: {numeric_columns}")
logger.info(f"Categorical columns: {categorical_columns}")
# Visualize distributions of numeric columns
for column in numeric_columns:
fig = px.histogram(df, x=column, title=f"Distribution of {column}")
fig.update_layout(
xaxis_title=column,
yaxis_title="Count",
legend_title="",
)
fig.show()
# Visualize relationships between numeric columns
if len(numeric_columns) >= 2:
for i in range(len(numeric_columns)):
for j in range(i + 1, len(numeric_columns)):
x_col: str = numeric_columns[i]
y_col: str = numeric_columns[j]
fig = px.scatter(
df,
x=x_col,
y=y_col,
title=f"{y_col} vs {x_col}",
trendline="ols"
)
fig.update_layout(
xaxis_title=x_col,
yaxis_title=y_col,
legend_title="",
)
fig.show()
# Visualize counts of categorical columns
for column in categorical_columns:
counts = df[column].value_counts().reset_index()
counts.columns = [column, 'Count']
fig = px.bar(
counts,
x=column,
y='Count',
title=f"Counts of {column}"
)
fig.update_layout(
xaxis_title=column,
yaxis_title="Count",
legend_title="",
)
fig.show()
# Visualize relationships between categorical and numeric columns
for cat_col in categorical_columns:
for num_col in numeric_columns:
fig = px.box(
df,
x=cat_col,
y=num_col,
title=f"{num_col} by {cat_col}"
)
fig.update_layout(
xaxis_title=cat_col,
yaxis_title=num_col,
legend_title="",
)
fig.show()
except Exception as error:
logger.error(f"An error occurred: {error}", exc_info=True)
if __name__ == "__main__":
# Example usage with default parameters
visualize_dataset(dataset_name="fka/awesome-chatgpt-prompts")
This script provides a generalized and reusable approach to loading any dataset using the datasets library and generating insightful visualizations with Plotly. Key features of the script include:
- PEP-8 Compliance: The code is formatted according to PEP-8 guidelines for readability and maintainability.
- Type Hints: Utilizes the
typing module to provide type annotations for better code clarity.
- Robust Error Handling: Implements try-except blocks with logging to capture and report exceptions without crashing.
- Scalability: Designed to handle datasets of various sizes and structures without hard-coded values.
- Zero Hard Coding: No hard-coded dataset-specific logic; works with any dataset that can be loaded into a pandas DataFrame.
- Insightful Visualizations:
- Histograms for numeric column distributions.
- Scatter plots with trend lines for relationships between numeric columns.
- Bar charts for categorical column counts.
- Box plots to show the distribution of numeric data across categories.
Usage Instructions:
- Loading Different Datasets: Change the
dataset_name parameter in the visualize_dataset function call to load and visualize a different dataset.
- Specifying Configurations and Splits: Use the
config_name and split_name parameters if the dataset requires a specific configuration or you wish to visualize a particular split.
Example:
visualize_dataset(
dataset_name="your_dataset_name",
config_name="your_config_name",
split_name="validation"
)
Replace "your_dataset_name", "your_config_name", and "validation" with the appropriate values for your dataset.
Note: Ensure that all required libraries are installed. You may need to install Plotly and datasets via pip:
pip install plotly datasets
Logging: The script uses the logging module to provide informational messages about the steps being performed, which is helpful for debugging and understanding the data processing flow.
By following this approach, you can visualize any dataset's structure and glean meaningful insights without manual adjustments or hard-coded parameters.