Spaces:
Sleeping
Sleeping
Download src/components/eda_visualizer.py from Sai-sathwik/MLOPS_LIFECYCLE: direct link, hf CLI and curl.
- Browser
- Download file 16.5 kB
-
https://huggingface.co/spaces/Sai-sathwik/MLOPS_LIFECYCLE/resolve/main/src/components/eda_visualizer.py
- Command line
-
hf download hf://spaces/Sai-sathwik/MLOPS_LIFECYCLE/src/components/eda_visualizer.py
-
curl -L -o eda_visualizer.py https://huggingface.co/spaces/Sai-sathwik/MLOPS_LIFECYCLE/resolve/main/src/components/eda_visualizer.py
16.5 kB
| """ | |
| 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) | |