import logging
from typing import List, Union
import pandas as pd
import plotly.express as px
from datasets import Dataset, DatasetDict, load_dataset
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def visualize_dataset(dataset_name: str) -> None:
"""
Load a dataset by name and create visualizations using Plotly.
Args:
dataset_name (str): The name of the dataset to load.
"""
try:
dataset = load_dataset(dataset_name)
if not isinstance(dataset, (DatasetDict, Dataset)):
raise ValueError(f"Loaded dataset is of unexpected type: {type(dataset)}")
except Exception as error:
logger.error(f"Failed to load dataset '{dataset_name}': {error}")
return
# Process each split in the dataset (e.g., 'train', 'test')
if isinstance(dataset, DatasetDict):
for split_name, split_dataset in dataset.items():
logger.info(f"Processing split '{split_name}'")
process_and_visualize_split(split_dataset, split_name)
elif isinstance(dataset, Dataset):
# Single split dataset
split_name = 'default'
process_and_visualize_split(dataset, split_name)
def process_and_visualize_split(
dataset_split: Dataset, split_name: str, max_rows: int = 10000
) -> None:
"""
Process a dataset split and create appropriate visualizations.
Args:
dataset_split (Dataset): The dataset split to process.
split_name (str): Name of the dataset split.
max_rows (int): Maximum number of rows to process for visualization.
"""
try:
if dataset_split.num_rows > max_rows:
logger.info(
f"Dataset split '{split_name}' has {dataset_split.num_rows} rows; "
f"sampling {max_rows} rows for visualization."
)
dataset_split = dataset_split.shuffle(seed=42).select(range(max_rows))
df = dataset_split.to_pandas()
except Exception as error:
logger.error(
f"Error converting dataset split '{split_name}' to DataFrame: {error}"
)
return
# Identify columns and their types
logger.info(f"Columns in split '{split_name}': {list(df.columns)}")
logger.info(f"Data types:\n{df.dtypes}")
# Visualize numerical columns
visualize_numerical_columns(df, split_name)
# Visualize categorical columns
visualize_categorical_columns(df, split_name)
# Visualize text columns
visualize_text_columns(df, split_name)
# Create interactive visualization
create_interactive_visualization(df, split_name)
def visualize_numerical_columns(df: pd.DataFrame, split_name: str) -> None:
"""
Visualize numerical columns with histograms.
Args:
df (pd.DataFrame): The DataFrame containing the data.
split_name (str): Name of the dataset split.
"""
num_cols = df.select_dtypes(include='number').columns.tolist()
if not num_cols:
logger.info("No numerical columns to visualize.")
return
for col in num_cols:
try:
fig = px.histogram(
df,
x=col,
title=f"Histogram of '{col}' ({split_name} split)",
)
fig.update_layout(xaxis_title=col, yaxis_title='Count')
fig.show()
except Exception as error:
logger.error(f"Error creating histogram for '{col}': {error}")
def visualize_categorical_columns(df: pd.DataFrame, split_name: str) -> None:
"""
Visualize categorical columns with bar charts.
Args:
df (pd.DataFrame): The DataFrame containing the data.
split_name (str): Name of the dataset split.
"""
cat_cols = df.select_dtypes(include='object').columns.tolist()
if not cat_cols:
logger.info("No categorical columns to visualize.")
return
for col in cat_cols:
unique_values = df[col].nunique()
if unique_values < 50:
try:
value_counts = df[col].value_counts().reset_index()
fig = px.bar(
value_counts,
x='index',
y=col,
title=f"Count of '{col}' values ({split_name} split)",
labels={'index': col, col: 'Count'},
)
fig.show()
except Exception as error:
logger.error(f"Error creating bar chart for '{col}': {error}")
else:
logger.info(
f"Skipping '{col}' - too many unique values ({unique_values})."
)
def visualize_text_columns(df: pd.DataFrame, split_name: str) -> None:
"""
Visualize text columns with word frequency plots.
Args:
df (pd.DataFrame): The DataFrame containing the data.
split_name (str): Name of the dataset split.
"""
import re
from collections import Counter
text_cols = df.select_dtypes(include='object').columns.tolist()
for col in text_cols:
if not df[col].apply(lambda x: isinstance(x, str)).all():
continue
try:
text_data = df[col].dropna().str.lower()
tokens = text_data.apply(lambda x: re.findall(r'\b\w+\b', x))
token_list = [token for sublist in tokens for token in sublist]
word_counts = Counter(token_list)
word_counts_df = pd.DataFrame(
word_counts.most_common(20), columns=['word', 'count']
)
fig = px.bar(
word_counts_df,
x='word',
y='count',
title=f"Top 20 words in '{col}' ({split_name} split)",
)
fig.show()
except Exception as error:
logger.error(f"Error creating word frequency plot for '{col}': {error}")
def create_interactive_visualization(df: pd.DataFrame, split_name: str) -> None:
"""
Create an interactive visualization with play and stop buttons.
Args:
df (pd.DataFrame): The DataFrame containing the data.
split_name (str): Name of the dataset split.
"""
num_cols = df.select_dtypes(include='number').columns.tolist()
if len(num_cols) >= 2:
try:
fig = px.scatter(
df,
x=num_cols[0],
y=num_cols[1],
animation_frame=df.index,
title=f"Animated Scatter Plot of '{num_cols[0]}' vs '{num_cols[1]}' "
f"({split_name} split)",
)
fig.update_layout(
xaxis_title=num_cols[0],
yaxis_title=num_cols[1],
)
fig.show()
except Exception as error:
logger.error(f"Error creating animated scatter plot: {error}")
else:
text_cols = df.select_dtypes(include='object').columns.tolist()
if not text_cols:
logger.info("No columns available for interactive visualization.")
return
col = text_cols[0]
try:
df['index'] = df.index
fig = px.scatter(
df,
x=[0] * len(df),
y=[0] * len(df),
size=[0] * len(df),
hover_data=[col],
animation_frame='index',
range_x=[-1, 1],
range_y=[-1, 1],
title=f"Row-wise Analysis of '{col}' ({split_name} split)",
)
fig.update_traces(marker={'opacity': 0})
fig.update_layout(showlegend=False, xaxis_visible=False, yaxis_visible=False)
fig.show()
except Exception as error:
logger.error(f"Error creating row-wise analysis for '{col}': {error}")
if __name__ == '__main__':
DATASET_NAME = 'fka/awesome-chatgpt-prompts'
visualize_dataset(DATASET_NAME)