Spaces:
Sleeping
Sleeping
File size: 16,475 Bytes
5e6746d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | """
EDA Visualizer β all Plotly charts with valid configurations.
No font size=0, no empty title with invalid font, no deprecated APIs.
"""
from __future__ import annotations
from typing import Dict, List, Optional
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from src.logger import get_logger
logger = get_logger(__name__)
# ββ Design tokens βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_C = {
"primary": "#8b5cf6",
"secondary": "#3b82f6",
"accent": "#10b981",
"warning": "#f59e0b",
"danger": "#ef4444",
"pink": "#ec4899",
"bg": "rgba(15,23,42,0.0)",
"plot_bg": "rgba(30,27,75,0.35)",
"text": "#cbd5e1",
"muted": "#64748b",
"grid": "rgba(139,92,246,0.12)",
"border": "rgba(139,92,246,0.2)",
}
_BASE_LAYOUT = dict(
paper_bgcolor=_C["bg"],
plot_bgcolor=_C["plot_bg"],
font=dict(family="Inter,system-ui,sans-serif", size=12, color=_C["text"]),
hoverlabel=dict(bgcolor="#1e1b4b", font_size=12, bordercolor=_C["border"]),
margin=dict(l=45, r=35, t=50, b=45),
)
_AXIS = dict(
gridcolor=_C["grid"], showgrid=True, zeroline=False,
linecolor=_C["border"], tickfont=dict(color=_C["muted"]),
)
def _apply(fig: go.Figure, title: str = "", height: int = 400) -> go.Figure:
"""Apply standard theme. Only set title if non-empty."""
layout_kw = dict(height=height, **_BASE_LAYOUT)
if title:
layout_kw["title"] = dict(
text=title,
font=dict(size=14, color="#e2e8f0"),
x=0.02,
)
fig.update_layout(**layout_kw)
fig.update_xaxes(**_AXIS)
fig.update_yaxes(**_AXIS)
return fig
class EDAVisualizer:
"""Generates all EDA visualisations with consistent dark theme."""
def __init__(self, df: pd.DataFrame) -> None:
self.df = df
self.numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
self.categorical_cols= df.select_dtypes(include=["object", "category"]).columns.tolist()
# ββ Missing values ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def missing_value_heatmap(self) -> go.Figure:
missing = (self.df.isnull().mean() * 100).round(2)
missing = missing[missing > 0].sort_values(ascending=False)
if missing.empty:
fig = go.Figure()
fig.add_annotation(
text="β No missing values found",
showarrow=False,
font=dict(size=15, color=_C["accent"]),
xref="paper", yref="paper", x=0.5, y=0.5,
)
return _apply(fig, "Missing Value Analysis", height=300)
fig = go.Figure(go.Bar(
x=missing.index.tolist(),
y=missing.values.tolist(),
marker=dict(
color=missing.values,
colorscale="Purples",
showscale=True,
colorbar=dict(title="%", tickfont=dict(color=_C["muted"])),
),
text=[f"{v:.1f}%" for v in missing.values],
textposition="outside",
textfont=dict(color=_C["text"]),
))
fig.update_layout(xaxis_tickangle=-45, yaxis_title="Missing (%)")
return _apply(fig, "Missing Value Analysis", height=380)
# ββ Distributions βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def distribution_plots(self, max_cols: int = 12) -> go.Figure:
cols = self.numeric_cols[:max_cols]
if not cols:
return go.Figure()
n_cols = 3
n_rows = (len(cols) + n_cols - 1) // n_cols
fig = make_subplots(
rows=n_rows, cols=n_cols,
subplot_titles=cols,
vertical_spacing=0.09, horizontal_spacing=0.07,
)
palette = px.colors.qualitative.Vivid
for idx, col in enumerate(cols):
r, c = idx // n_cols + 1, idx % n_cols + 1
fig.add_trace(
go.Histogram(
x=self.df[col].dropna(),
name=col, showlegend=False,
marker_color=palette[idx % len(palette)],
opacity=0.82, nbinsx=30,
),
row=r, col=c,
)
fig.update_layout(height=280 * n_rows, **_BASE_LAYOUT)
# Update all subplot axes
fig.update_xaxes(**_AXIS)
fig.update_yaxes(**_AXIS)
# Fix subplot titles colour
for ann in fig.layout.annotations:
ann.font = dict(size=11, color=_C["muted"])
return fig
# ββ Correlation matrix ββββββββββββββββββββββββββββββββββββββββββββββββββββ
def correlation_matrix(self) -> go.Figure:
if len(self.numeric_cols) < 2:
return go.Figure()
corr = self.df[self.numeric_cols].corr().round(3)
fig = go.Figure(go.Heatmap(
z=corr.values,
x=corr.columns.tolist(),
y=corr.index.tolist(),
colorscale=[[0, "#7c3aed"], [0.5, "#1e1b4b"], [1, "#0891b2"]],
zmid=0, zmin=-1, zmax=1,
text=corr.round(2).values,
texttemplate="%{text}",
textfont=dict(size=9),
colorbar=dict(
title="r",
tickfont=dict(color=_C["muted"]),
titlefont=dict(color=_C["muted"]),
),
))
fig.update_layout(xaxis_tickangle=-45)
return _apply(fig, "Correlation Matrix", height=max(420, 55 * len(self.numeric_cols)))
# ββ Target analysis βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def target_analysis(self, target_col: str, task_type: str = "regression") -> go.Figure:
if target_col not in self.df.columns:
return go.Figure()
target = self.df[target_col].dropna()
palette = [_C["primary"], _C["secondary"], _C["accent"], _C["warning"], _C["pink"]] * 5
if task_type == "regression":
fig = make_subplots(
rows=1, cols=2,
subplot_titles=["Distribution", "Box Plot"],
horizontal_spacing=0.1,
)
fig.add_trace(
go.Histogram(x=target, nbinsx=40, marker_color=_C["accent"],
opacity=0.85, name=target_col),
row=1, col=1,
)
fig.add_trace(
go.Box(y=target, marker_color=_C["secondary"], boxmean=True, name=target_col),
row=1, col=2,
)
else:
counts = target.value_counts()
fig = make_subplots(
rows=1, cols=2,
subplot_titles=["Class Count", "Class Proportion"],
horizontal_spacing=0.1,
specs=[[{"type": "bar"}, {"type": "pie"}]],
)
fig.add_trace(
go.Bar(x=[str(c) for c in counts.index], y=counts.values,
marker_color=palette[:len(counts)],
text=counts.values, textposition="outside",
textfont=dict(color=_C["text"])),
row=1, col=1,
)
fig.add_trace(
go.Pie(labels=[str(c) for c in counts.index], values=counts.values,
hole=0.45, marker_colors=palette[:len(counts)]),
row=1, col=2,
)
fig.update_layout(height=380, **_BASE_LAYOUT)
fig.update_xaxes(**_AXIS)
fig.update_yaxes(**_AXIS)
for ann in fig.layout.annotations:
ann.font = dict(size=11, color=_C["muted"])
return fig
# ββ Outlier box plots βββββββββββββββββββββββββββββββββββββββββββββββββββββ
def outlier_boxplots(self, max_cols: int = 14) -> go.Figure:
cols = self.numeric_cols[:max_cols]
if not cols:
return go.Figure()
palette = px.colors.qualitative.Bold
fig = go.Figure()
for i, col in enumerate(cols):
fig.add_trace(go.Box(
y=self.df[col].dropna(), name=col,
marker_color=palette[i % len(palette)],
boxmean=True, whiskerwidth=0.5,
))
fig.update_layout(showlegend=False, xaxis_tickangle=-35)
return _apply(fig, "Outlier Detection β Box Plots", height=450)
# ββ Categorical analysis ββββββββββββββββββββββββββββββββββββββββββββββββββ
def categorical_analysis(self, max_cols: int = 6) -> go.Figure:
cols = self.categorical_cols[:max_cols]
if not cols:
fig = go.Figure()
fig.add_annotation(
text="No categorical columns found", showarrow=False,
font=dict(size=14, color=_C["muted"]),
xref="paper", yref="paper", x=0.5, y=0.5,
)
return _apply(fig, "Categorical Analysis", height=300)
n_cols = min(2, len(cols))
n_rows = (len(cols) + n_cols - 1) // n_cols
fig = make_subplots(
rows=n_rows, cols=n_cols,
subplot_titles=cols,
vertical_spacing=0.12, horizontal_spacing=0.1,
)
for idx, col in enumerate(cols):
r, c = idx // n_cols + 1, idx % n_cols + 1
counts = self.df[col].value_counts().head(15)
fig.add_trace(
go.Bar(
x=[str(v) for v in counts.index], y=counts.values,
marker_color=_C["primary"], opacity=0.85,
showlegend=False,
),
row=r, col=c,
)
fig.update_layout(height=320 * n_rows, **_BASE_LAYOUT)
fig.update_xaxes(**_AXIS, tickangle=-30)
fig.update_yaxes(**_AXIS)
for ann in fig.layout.annotations:
ann.font = dict(size=11, color=_C["muted"])
return fig
# ββ Feature importance ββββββββββββββββββββββββββββββββββββββββββββββββββββ
def feature_importance_plot(self, importances: Dict[str, float]) -> go.Figure:
if not importances:
return go.Figure()
sorted_items = sorted(importances.items(), key=lambda x: x[1])[-20:]
features = [i[0] for i in sorted_items]
values = [i[1] for i in sorted_items]
fig = go.Figure(go.Bar(
x=values, y=features,
orientation="h",
marker=dict(color=values, colorscale="Purples", showscale=False),
text=[f"{v:.4f}" for v in values],
textposition="outside",
textfont=dict(color=_C["text"]),
))
fig.update_layout(xaxis_title="Importance Score", yaxis_title="Feature")
return _apply(fig, "Feature Importance", height=max(400, 30 * len(features)))
# ββ Pairwise scatter ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def pairwise_scatter(
self, target_col: Optional[str] = None, max_features: int = 5
) -> go.Figure:
cols = self.numeric_cols[:max_features]
if len(cols) < 2:
return go.Figure()
color_col = (
target_col
if target_col and target_col in self.df.columns
and self.df[target_col].nunique() <= 20
else None
)
plot_cols = cols + ([color_col] if color_col else [])
fig = px.scatter_matrix(
self.df[plot_cols],
dimensions=cols,
color=color_col,
color_continuous_scale="Viridis",
opacity=0.5,
)
fig.update_traces(diagonal_visible=True, showupperhalf=False, marker_size=3)
fig.update_layout(height=700, **_BASE_LAYOUT)
return fig
# ββ Residual plot βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def residual_plot(self, y_true: list, y_pred: list) -> go.Figure:
y_true = np.asarray(y_true, dtype=float)
y_pred = np.asarray(y_pred, dtype=float)
residuals = y_true - y_pred
fig = make_subplots(
rows=1, cols=2,
subplot_titles=["Predicted vs Actual", "Residual Distribution"],
horizontal_spacing=0.1,
)
fig.add_trace(
go.Scatter(
x=y_pred.tolist(), y=y_true.tolist(), mode="markers",
marker=dict(color=_C["primary"], opacity=0.5, size=5),
name="Predictions",
),
row=1, col=1,
)
ref = [float(min(y_true.min(), y_pred.min())), float(max(y_true.max(), y_pred.max()))]
fig.add_trace(
go.Scatter(x=ref, y=ref, mode="lines",
line=dict(color=_C["warning"], dash="dash", width=1.5),
name="Perfect fit"),
row=1, col=1,
)
fig.add_trace(
go.Histogram(x=residuals.tolist(), nbinsx=40,
marker_color=_C["secondary"], opacity=0.78,
name="Residuals"),
row=1, col=2,
)
fig.update_layout(height=400, showlegend=False, **_BASE_LAYOUT)
fig.update_xaxes(**_AXIS)
fig.update_yaxes(**_AXIS)
for ann in fig.layout.annotations:
ann.font = dict(size=11, color=_C["muted"])
return fig
# ββ ROC curve βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def roc_curve_plot(self, roc_data: Dict) -> go.Figure:
fig = go.Figure()
fig.add_trace(go.Scatter(
x=roc_data["fpr"], y=roc_data["tpr"],
mode="lines",
line=dict(color=_C["primary"], width=2.5),
name=f"ROC (AUC = {roc_data['auc']:.3f})",
fill="tozeroy", fillcolor="rgba(139,92,246,0.09)",
))
fig.add_trace(go.Scatter(
x=[0, 1], y=[0, 1], mode="lines",
line=dict(color=_C["muted"], dash="dash", width=1.5),
name="Random classifier",
))
fig.update_layout(xaxis_title="False Positive Rate", yaxis_title="True Positive Rate")
return _apply(fig, "ROC Curve", height=420)
# ββ Confusion matrix ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def confusion_matrix_plot(
self, cm: np.ndarray, labels: Optional[list] = None
) -> go.Figure:
labels = labels or [str(i) for i in range(len(cm))]
row_sum = cm.sum(axis=1, keepdims=True)
# Avoid division by zero on empty rows
row_sum = np.where(row_sum == 0, 1, row_sum)
cm_pct = cm.astype(float) / row_sum * 100
text = [
[f"{cm[i, j]}<br>({cm_pct[i, j]:.1f}%)" for j in range(len(cm[i]))]
for i in range(len(cm))
]
fig = go.Figure(go.Heatmap(
z=cm_pct, x=labels, y=labels,
colorscale="Purples",
text=text, texttemplate="%{text}", textfont=dict(size=12),
showscale=True,
colorbar=dict(title="%", tickfont=dict(color=_C["muted"])),
))
fig.update_layout(xaxis_title="Predicted", yaxis_title="Actual")
return _apply(fig, "Confusion Matrix", height=430)
|