{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# \ud83d\udca1 Matplotlib Practice Exercise 2: Solutions & Walkthroughs\n", "\n", "This notebook contains **15 scenario-based challenges** reflecting real-world data engineering, machine learning diagnostics, and publication visualization tasks:\n", "- Machine Learning convergence curves and automated early stopping callouts\n", "- Multi-class Confusion Matrix heatmaps with normalized recall percentages\n", "- ROC curves with Area Under Curve (AUC) and Precision-Recall curves with $F_1$ iso-contours\n", "- Feature importance rankings with tree-variance error bars\n", "- Complex multi-panel analytical dashboards via `subplot_mosaic()`\n", "- Non-linear classification decision boundaries with probability contours\n", "- Time series volatility with rolling moving averages and Bollinger Bands\n", "- Customer cohort retention heatmaps\n", "- Big Data high-density Hexbin visualizations\n", "- Polar radar charts for multi-attribute model profiling\n", "- Classifier calibration reliability diagrams with Brier score\n", "- 3D optimization surfaces with gradient descent optimization paths\n", "- Memory-safe high-throughput batch plotting pipelines\n", "\n", "---\n", "*Tip: Complete solutions are available in `05_matplotlib_exercise_2_solutions.ipynb`.*\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 1: ML Convergence Dynamics with Early Stopping Annotation\n", "\n", "Given training and validation loss values across 40 epochs:\n", "```python\n", "epochs = np.arange(1, 41)\n", "train_loss = 1.9 * np.exp(-epochs / 8.0) + 0.15 + np.random.normal(0, 0.02, 40)\n", "val_loss = 2.0 * np.exp(-epochs / 9.0) + 0.32 + 0.0012 * (epochs - 16)**2 + np.random.normal(0, 0.025, 40)\n", "```\n", "1. Plot Train and Validation losses on the same Axes.\n", "2. Programmatically identify the epoch where validation loss reaches its minimum.\n", "3. Draw a dashed green vertical line at this optimal epoch.\n", "4. Use `ax.annotate()` with a curved arrow pointing directly to the minimum point, displaying the optimal epoch and loss value.\n", "5. Shade the region after epoch 20 in light orange to highlight the overfitting regime.\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 1 completed: Convergence curves with early stopping marker and overfitting band\n" ] } ], "source": [ "epochs = np.arange(1, 41)\n", "train_loss = 1.9 * np.exp(-epochs / 8.0) + 0.15 + np.random.normal(0, 0.02, 40)\n", "val_loss = 2.0 * np.exp(-epochs / 9.0) + 0.32 + 0.0012 * (epochs - 16)**2 + np.random.normal(0, 0.025, 40)\n", "\n", "fig, ax = plt.subplots(figsize=(9, 4.8), dpi=100)\n", "ax.plot(epochs, train_loss, color='#2b5c8f', lw=2, label='Train Loss')\n", "ax.plot(epochs, val_loss, color='#d95f02', lw=2, label='Validation Loss')\n", "\n", "opt_idx = np.argmin(val_loss)\n", "opt_epoch = epochs[opt_idx]\n", "opt_val = val_loss[opt_idx]\n", "\n", "ax.axvline(opt_epoch, color='#2ca02c', linestyle='--', lw=1.8, label=f'Optimal Epoch ({opt_epoch})')\n", "ax.axvspan(20, 40, color='#d95f02', alpha=0.1, label='Overfitting Zone')\n", "\n", "ax.annotate(\n", " f'Min Val Loss: {opt_val:.3f}\\nEpoch {opt_epoch}',\n", " xy=(opt_epoch, opt_val),\n", " xytext=(opt_epoch + 5, opt_val + 0.35),\n", " arrowprops=dict(arrowstyle='->', color='black', lw=1.5, connectionstyle='arc3,rad=-0.2'),\n", " bbox=dict(boxstyle='round,pad=0.4', facecolor='#ffffcc', edgecolor='#cccc00', alpha=0.9),\n", " fontweight='bold', fontsize=9\n", ")\n", "\n", "ax.set_title(\"Training & Validation Loss with Automated Early Stopping Detection\", fontweight='bold')\n", "ax.set_xlabel(\"Epoch\")\n", "ax.set_ylabel(\"Cross-Entropy Loss\")\n", "ax.grid(True, linestyle=':', alpha=0.5)\n", "ax.legend(loc='upper right')\n", "ax.spines[['top', 'right']].set_visible(False)\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 2: Normalized Multi-Class Confusion Matrix Heatmap\n", "\n", "Given a 4x4 Confusion Matrix representing predictions across 4 medical diagnosis categories:\n", "```python\n", "labels = ['Healthy', 'Mild', 'Moderate', 'Severe']\n", "cm = np.array([\n", " [142, 12, 4, 2],\n", " [ 15, 98, 14, 3],\n", " [ 5, 18, 82, 15],\n", " [ 1, 4, 11, 64]\n", "])\n", "```\n", "1. Calculate the row-normalized percentage matrix (Recall % per class).\n", "2. Render the normalized matrix using `ax.imshow()` with `cmap='Blues'` and `vmin=0, vmax=100`.\n", "3. Overlay text inside each cell showing both the normalized percentage and the raw count (e.g. `88.8%\\n(142)`).\n", "4. Set text color dynamically to white for dark cells (>50%) and black for light cells.\n", "5. Add a colorbar and appropriate axis labels.\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 2 completed: Confusion matrix heatmap with dynamic high-contrast text labels\n" ] } ], "source": [ "labels = ['Healthy', 'Mild', 'Moderate', 'Severe']\n", "cm = np.array([\n", " [142, 12, 4, 2],\n", " [ 15, 98, 14, 3],\n", " [ 5, 18, 82, 15],\n", " [ 1, 4, 11, 64]\n", "])\n", "cm_norm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] * 100\n", "\n", "fig, ax = plt.subplots(figsize=(7, 6), dpi=100)\n", "im = ax.imshow(cm_norm, cmap='Blues', vmin=0, vmax=100, interpolation='nearest')\n", "\n", "ax.set_xticks(np.arange(len(labels)))\n", "ax.set_yticks(np.arange(len(labels)))\n", "ax.set_xticklabels(labels, fontsize=10)\n", "ax.set_yticklabels(labels, fontsize=10)\n", "ax.set_xlabel(\"Predicted Label\", fontweight='semibold')\n", "ax.set_ylabel(\"True Ground Truth\", fontweight='semibold')\n", "\n", "for i in range(len(labels)):\n", " for j in range(len(labels)):\n", " col = 'white' if cm_norm[i, j] > 50 else 'black'\n", " ax.text(j, i, f\"{cm_norm[i, j]:.1f}%\\n({cm[i, j]})\",\n", " ha='center', va='center', color=col, fontweight='bold', fontsize=9)\n", "\n", "cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)\n", "cbar.set_label(\"Recall Rate (%)\")\n", "ax.set_title(\"Multi-Class Diagnostic Confusion Matrix\", fontweight='bold', pad=12)\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 3: ROC Curve with AUC Score & Random Chance Baseline\n", "\n", "Given FPR and TPR evaluation coordinates for two competing models:\n", "```python\n", "fpr = np.linspace(0, 1, 100)\n", "tpr_rf = 1.0 / (1.0 + np.exp(-7 * (fpr - 0.18)))\n", "tpr_rf[0] = 0.0\n", "auc_rf = 0.941\n", "\n", "tpr_lr = 1.0 / (1.0 + np.exp(-4 * (fpr - 0.28)))\n", "tpr_lr[0] = 0.0\n", "auc_lr = 0.812\n", "```\n", "1. Plot both ROC curves with distinct colors and line thicknesses.\n", "2. Fill the area under the top-performing Random Forest curve with light blue (`alpha=0.15`).\n", "3. Plot the random guessing diagonal baseline $y = x$ with a dashed gray line.\n", "4. Include AUC scores directly inside the legend labels.\n", "5. Set limits to `[-0.02, 1.02]` and grid on.\n" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 3 completed: Multi-model ROC curves with shaded AUC and chance baseline\n" ] } ], "source": [ "fpr = np.linspace(0, 1, 100)\n", "tpr_rf = 1.0 / (1.0 + np.exp(-7 * (fpr - 0.18)))\n", "tpr_rf[0] = 0.0\n", "auc_rf = 0.941\n", "\n", "tpr_lr = 1.0 / (1.0 + np.exp(-4 * (fpr - 0.28)))\n", "tpr_lr[0] = 0.0\n", "auc_lr = 0.812\n", "\n", "fig, ax = plt.subplots(figsize=(7, 6), dpi=100)\n", "ax.plot(fpr, tpr_rf, color='#2b5c8f', lw=2.5, label=f'Random Forest (AUC = {auc_rf:.3f})')\n", "ax.plot(fpr, tpr_lr, color='#d95f02', lw=2.0, label=f'Logistic Regression (AUC = {auc_lr:.3f})')\n", "ax.fill_between(fpr, 0, tpr_rf, color='#2b5c8f', alpha=0.15)\n", "ax.plot([0, 1], [0, 1], 'k--', lw=1.2, label='Random Baseline (AUC = 0.500)')\n", "\n", "ax.set_title(\"Receiver Operating Characteristic (ROC) Comparison\", fontweight='bold')\n", "ax.set_xlabel(\"False Positive Rate (1 - Specificity)\")\n", "ax.set_ylabel(\"True Positive Rate (Sensitivity / Recall)\")\n", "ax.set_xlim(-0.02, 1.02)\n", "ax.set_ylim(-0.02, 1.02)\n", "ax.grid(True, linestyle=':', alpha=0.5)\n", "ax.legend(loc='lower right', frameon=True)\n", "ax.spines[['top', 'right']].set_visible(False)\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 4: Precision-Recall Curve with F1 Score Iso-Curves\n", "\n", "In heavily imbalanced fraud detection, Precision-Recall curves are superior to ROC curves.\n", "1. Plot a simulated Precision-Recall curve:\n", " `recall = np.linspace(0.01, 1.0, 100)`\n", " `precision = 1.0 - 0.65 * recall**2`\n", "2. Overlay **$F_1$ Iso-Contours**: Curves where $F_1 = \\frac{2 \\cdot P \\cdot R}{P + R} = c$.\n", " For each $f_1 \\in [0.2, 0.4, 0.6, 0.8]$:\n", " Compute $P = \\frac{f_1 \\cdot R}{2R - f_1}$ for $R > f_1 / 2$.\n", " Plot dashed gray lines and label each contour with its $F_1$ value.\n", "3. Label axes and set limits to $[0, 1.05]$.\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 4 completed: Precision-recall curve with F1 score iso-contours\n" ] } ], "source": [ "recall = np.linspace(0.01, 1.0, 100)\n", "precision = 1.0 - 0.65 * recall**2\n", "\n", "fig, ax = plt.subplots(figsize=(7, 6), dpi=100)\n", "\n", "# Plot F1 iso-contours\n", "for f1 in [0.2, 0.4, 0.6, 0.8]:\n", " r_vals = np.linspace(f1 / 2 + 0.01, 1.0, 100)\n", " p_vals = (f1 * r_vals) / (2 * r_vals - f1)\n", " ax.plot(r_vals, p_vals, color='gray', linestyle=':', lw=1.0)\n", " ax.text(r_vals[-1] + 0.01, p_vals[-1], f'F1={f1:.1f}', color='gray', fontsize=8, va='center')\n", "\n", "ax.plot(recall, precision, color='#2b5c8f', lw=2.5, label='Fraud Detection Classifier')\n", "ax.fill_between(recall, 0, precision, color='#2b5c8f', alpha=0.15)\n", "\n", "ax.set_title(\"Precision-Recall Curve with F1 Iso-Contours\", fontweight='bold')\n", "ax.set_xlabel(\"Recall\")\n", "ax.set_ylabel(\"Precision\")\n", "ax.set_xlim(0, 1.08)\n", "ax.set_ylim(0, 1.08)\n", "ax.grid(True, linestyle=':', alpha=0.4)\n", "ax.legend(loc='lower left')\n", "ax.spines[['top', 'right']].set_visible(False)\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 5: Sorted Feature Importance with Tree-Variance Error Bars\n", "\n", "Given 7 feature importances and their standard deviations computed across 100 decision trees:\n", "```python\n", "features = ['Seniority', 'Credit Limit', 'Transactions', 'Debt Ratio', 'Age', 'Savings', 'Delinquency']\n", "importances = np.array([0.08, 0.26, 0.19, 0.14, 0.06, 0.16, 0.11])\n", "std_devs = np.array([0.015, 0.035, 0.025, 0.020, 0.012, 0.022, 0.018])\n", "```\n", "1. Sort features ascending by importance.\n", "2. Create a horizontal bar chart (`ax.barh`) with `xerr=std_devs` and `capsize=4`.\n", "3. Set error bar line color to red and bar face color to steel blue.\n", "4. Annotate the exact mean value next to each bar.\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 5 completed: Sorted horizontal feature importance with variance error bars\n" ] } ], "source": [ "features = np.array(['Seniority', 'Credit Limit', 'Transactions', 'Debt Ratio', 'Age', 'Savings', 'Delinquency'])\n", "importances = np.array([0.08, 0.26, 0.19, 0.14, 0.06, 0.16, 0.11])\n", "std_devs = np.array([0.015, 0.035, 0.025, 0.020, 0.012, 0.022, 0.018])\n", "\n", "idx = np.argsort(importances)\n", "fig, ax = plt.subplots(figsize=(8, 4.8), dpi=100)\n", "bars = ax.barh(features[idx], importances[idx], xerr=std_devs[idx], color='#2b5c8f', edgecolor='black',\n", " height=0.55, capsize=4, error_kw={'ecolor': '#d95f02', 'elinewidth': 1.5})\n", "\n", "for bar in bars:\n", " w = bar.get_width()\n", " ax.text(w + 0.045, bar.get_y() + bar.get_height()/2.0, f\"{w:.2f}\",\n", " va='center', ha='left', fontsize=9, fontweight='bold')\n", "\n", "ax.set_xlim(0, 0.36)\n", "ax.set_title(\"Random Forest Feature Importance with Ensemble Variance\", fontweight='bold')\n", "ax.set_xlabel(\"Mean Gini Decrease (MDI)\")\n", "ax.grid(axis='x', linestyle=':', alpha=0.5)\n", "ax.spines[['top', 'right']].set_visible(False)\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 6: Asymmetric Multi-Panel Dashboard via `subplot_mosaic`\n", "\n", "Build a 3-panel analytics dashboard using `plt.subplot_mosaic()` with layout:\n", "```python\n", "blueprint = [\n", " [\"summary\", \"detail_top\"],\n", " [\"summary\", \"detail_bot\"]\n", "]\n", "```\n", "With `width_ratios=[2, 1]`:\n", "- `\"summary\"` (Left): Scatter plot of 150 points ($x, y$) with linear regression trendline.\n", "- `\"detail_top\"` (Top Right): Histogram of residuals ($y - \\hat{y}$).\n", "- `\"detail_bot\"` (Bottom Right): Line plot of rolling mean of residuals.\n", "Use `layout='constrained'` and set clean titles on each panel.\n" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 6 completed: Multi-panel regression diagnostics dashboard\n" ] } ], "source": [ "blueprint = [\n", " [\"summary\", \"detail_top\"],\n", " [\"summary\", \"detail_bot\"]\n", "]\n", "\n", "rng = np.random.default_rng(42)\n", "x_pts = np.linspace(1, 10, 100)\n", "y_pts = 2.5 * x_pts + 5 + rng.normal(0, 3, 100)\n", "\n", "slope, intercept = np.polyfit(x_pts, y_pts, 1)\n", "y_pred = slope * x_pts + intercept\n", "residuals = y_pts - y_pred\n", "\n", "fig, axd = plt.subplot_mosaic(blueprint, figsize=(11, 5.5), layout='constrained', gridspec_kw={'width_ratios': [2, 1]})\n", "\n", "# 1. Summary\n", "axd['summary'].scatter(x_pts, y_pts, color='#2b5c8f', alpha=0.6, edgecolors='none', label='Observations')\n", "axd['summary'].plot(x_pts, y_pred, color='red', lw=2, label=f'Fit: y = {slope:.2f}x + {intercept:.2f}')\n", "axd['summary'].set_title(\"Primary Regression Fit\", fontweight='bold')\n", "axd['summary'].grid(True, linestyle=':', alpha=0.5)\n", "axd['summary'].legend()\n", "\n", "# 2. Detail Top (Hist)\n", "axd['detail_top'].hist(residuals, bins=15, color='#e27d60', edgecolor='white')\n", "axd['detail_top'].set_title(\"Residual Error Distribution\", fontsize=10, fontweight='bold')\n", "axd['detail_top'].grid(True, linestyle=':', alpha=0.5)\n", "\n", "# 3. Detail Bot (Rolling residual)\n", "rolling_res = np.convolve(residuals, np.ones(5)/5, mode='valid')\n", "axd['detail_bot'].plot(rolling_res, color='#41b3a3', lw=1.8)\n", "axd['detail_bot'].axhline(0, color='gray', linestyle='--')\n", "axd['detail_bot'].set_title(\"Rolling Mean Residual\", fontsize=10, fontweight='bold')\n", "axd['detail_bot'].grid(True, linestyle=':', alpha=0.5)\n", "\n", "fig.suptitle(\"Linear Model Diagnostics Dashboard (subplot_mosaic)\", fontsize=13, fontweight='bold')\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 7: Machine Learning Decision Boundary with Probability Contours\n", "\n", "Simulate a 2D classification dataset with two concentric ring clusters (e.g. circle dataset):\n", "1. Create a 2D meshgrid over $X_1, X_2 \\\\in [-2.5, 2.5]$.\n", "2. Compute model probability: $P = \\\\sigma(1.5(X_1^2 + X_2^2 - 2.0))$.\n", "3. Render filled contour confidence regions with `ax.contourf(..., cmap='RdBu_r', levels=20, alpha=0.6)`.\n", "4. Draw the critical decision boundary $P = 0.5$ in solid black with `linewidth=2.5`.\n", "5. Scatter sample points for Class 0 (inside ring) and Class 1 (outside ring).\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 7 completed: Non-linear decision boundary with filled probability field\n" ] } ], "source": [ "rng = np.random.default_rng(2026)\n", "x1_grid = np.linspace(-2.5, 2.5, 200)\n", "x2_grid = np.linspace(-2.5, 2.5, 200)\n", "X1, X2 = np.meshgrid(x1_grid, x2_grid)\n", "\n", "# Probability function: Inner circle is Class 0, Outer is Class 1\n", "Z_logits = 1.5 * (X1**2 + X2**2 - 2.0)\n", "P_class1 = 1.0 / (1.0 + np.exp(-Z_logits))\n", "\n", "fig, ax = plt.subplots(figsize=(7.5, 6), dpi=100)\n", "cf = ax.contourf(X1, X2, P_class1, levels=20, cmap='RdBu_r', alpha=0.6)\n", "cs = ax.contour(X1, X2, P_class1, levels=[0.5], colors='black', linewidths=2.5)\n", "ax.clabel(cs, fmt='P=0.5 (Boundary)', fontsize=9)\n", "\n", "# Scatter points\n", "r_in = rng.uniform(0, 1.2, 60)\n", "theta_in = rng.uniform(0, 2*np.pi, 60)\n", "ax.scatter(r_in * np.cos(theta_in), r_in * np.sin(theta_in), color='#2166ac', edgecolors='white', label='Class 0 (Core)')\n", "\n", "r_out = rng.uniform(1.6, 2.4, 60)\n", "theta_out = rng.uniform(0, 2*np.pi, 60)\n", "ax.scatter(r_out * np.cos(theta_out), r_out * np.sin(theta_out), color='#b2182b', edgecolors='white', label='Class 1 (Perimeter)')\n", "\n", "cbar = fig.colorbar(cf, ax=ax)\n", "cbar.set_label(\"Predicted Class 1 Probability\")\n", "ax.set_title(\"Non-Linear Radial Decision Boundary & Confidence Field\", fontweight='bold')\n", "ax.legend(loc='lower left')\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 8: Financial Time Series with Rolling Average & Bollinger Bands\n", "\n", "Given 90 days of simulated stock prices:\n", "```python\n", "days = np.arange(1, 91)\n", "prices = 100 + np.cumsum(np.random.normal(0.2, 1.5, 90))\n", "```\n", "1. Compute the 7-day rolling moving average $\\mu_7$ and 7-day rolling standard deviation $\\sigma_7$.\n", "2. Plot the raw daily closing price with a thin gray line.\n", "3. Plot the 7-day moving average in bold navy.\n", "4. Shade the **Bollinger Band** ($\\mu_7 \\\\pm 2\\\\sigma_7$) in light blue with `alpha=0.2`.\n", "5. Annotate the maximum price point on the chart with a pointer arrow.\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 8 completed: Time series with 7-day rolling mean, Bollinger bands, and peak annotation\n" ] } ], "source": [ "days = np.arange(1, 91)\n", "prices = 100 + np.cumsum(np.random.normal(0.2, 1.5, 90))\n", "\n", "# Compute rolling stats (window = 7)\n", "w = 7\n", "rolling_mean = np.convolve(prices, np.ones(w)/w, mode='valid')\n", "rolling_std = np.array([np.std(prices[i:i+w]) for i in range(len(prices) - w + 1)])\n", "rolling_days = days[w-1:]\n", "\n", "fig, ax = plt.subplots(figsize=(9, 4.8), dpi=100)\n", "ax.plot(days, prices, color='#888888', lw=1.2, label='Daily Close')\n", "ax.plot(rolling_days, rolling_mean, color='#1f77b4', lw=2.2, label='7-Day Moving Avg (SMA)')\n", "ax.fill_between(rolling_days, rolling_mean - 2*rolling_std, rolling_mean + 2*rolling_std,\n", " color='#1f77b4', alpha=0.18, label=r'Bollinger Band ($\\mu \\pm 2\\sigma$)')\n", "\n", "max_idx = np.argmax(prices)\n", "ax.annotate(f'Peak: ${prices[max_idx]:.2f}',\n", " xy=(days[max_idx], prices[max_idx]),\n", " xytext=(days[max_idx] - 12, prices[max_idx] + 4),\n", " arrowprops=dict(arrowstyle='->', color='black', lw=1.5),\n", " bbox=dict(boxstyle='round,pad=0.3', facecolor='#ffffcc', edgecolor='gray'),\n", " fontweight='bold', fontsize=9)\n", "\n", "ax.set_title(\"Asset Volatility Analysis: 7-Day SMA & Bollinger Bands\", fontweight='bold')\n", "ax.set_xlabel(\"Trading Day\")\n", "ax.set_ylabel(\"Price ($USD)\")\n", "ax.grid(True, linestyle=':', alpha=0.5)\n", "ax.legend(loc='upper left')\n", "ax.spines[['top', 'right']].set_visible(False)\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 9: Customer Cohort Retention Triangular Heatmap\n", "\n", "Given a monthly customer retention cohort matrix (percentages over 5 months):\n", "```python\n", "cohorts = ['Jan', 'Feb', 'Mar', 'Apr', 'May']\n", "retention = np.array([\n", " [100, 42, 34, 28, 25],\n", " [100, 45, 36, 30, np.nan],\n", " [100, 48, 39, np.nan, np.nan],\n", " [100, 50, np.nan, np.nan, np.nan],\n", " [100, np.nan, np.nan, np.nan, np.nan]\n", "])\n", "```\n", "1. Render the matrix using `ax.imshow()` with `cmap='Greens'` and `vmin=0, vmax=100`.\n", "2. Format invalid/unborn future months (`np.nan`) cleanly with white background.\n", "3. Stamp the exact retention percentage `f\\\"{val:.0f}%\\\"` on all valid cells with appropriate contrasting text color.\n", "4. Set X-axis tick labels to `['Month 0', 'Month 1', 'Month 2', 'Month 3', 'Month 4']` and Y-axis to cohort names.\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 9 completed: Customer cohort retention matrix with masked NaNs and percentage labels\n" ] } ], "source": [ "cohorts = ['Jan', 'Feb', 'Mar', 'Apr', 'May']\n", "retention = np.array([\n", " [100, 42, 34, 28, 25],\n", " [100, 45, 36, 30, np.nan],\n", " [100, 48, 39, np.nan, np.nan],\n", " [100, 50, np.nan, np.nan, np.nan],\n", " [100, np.nan, np.nan, np.nan, np.nan]\n", "])\n", "\n", "fig, ax = plt.subplots(figsize=(7, 5.5), dpi=100)\n", "# Mask NaNs\n", "masked_ret = np.ma.masked_invalid(retention)\n", "im = ax.imshow(masked_ret, cmap='Greens', vmin=0, vmax=100, interpolation='nearest')\n", "\n", "ax.set_xticks(np.arange(5))\n", "ax.set_yticks(np.arange(5))\n", "ax.set_xticklabels([f'Month {i}' for i in range(5)], fontweight='semibold')\n", "ax.set_yticklabels(cohorts, fontweight='semibold')\n", "ax.set_ylabel(\"Cohort Signup Month\", fontweight='bold')\n", "\n", "for i in range(5):\n", " for j in range(5):\n", " val = retention[i, j]\n", " if not np.isnan(val):\n", " col = 'white' if val > 55 else 'black'\n", " ax.text(j, i, f\"{val:.0f}%\", ha='center', va='center', color=col, fontweight='bold', fontsize=10)\n", "\n", "cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)\n", "cbar.set_label(\"Retention Rate (%)\")\n", "ax.set_title(\"Customer Cohort Retention Rate (%)\", fontweight='bold', pad=12)\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 10: 2D Hexbin Density Visualization with Logarithmic Counts\n", "\n", "When visualizing massive geospatial or telemetry datasets (50,000+ points), individual scatter dots cause total visual occlusion.\n", "1. Generate 50,000 points from a correlated bivariate Gaussian distribution:\n", " `x = rng.normal(0, 1.5, 50000)`\n", " `y = 0.8 * x + rng.normal(0, 0.8, 50000)`\n", "2. Render a hexagonal bin density plot using `ax.hexbin(x, y, gridsize=40, cmap='inferno', bins='log')`.\n", "3. Attach a colorbar with label `'Log10(Point Count)'`.\n", "4. Set title and remove chart junk.\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 10 completed: Log-scaled 2D hexbin density chart\n" ] } ], "source": [ "rng = np.random.default_rng(42)\n", "x_big = rng.normal(0, 1.5, 50000)\n", "y_big = 0.8 * x_big + rng.normal(0, 0.8, 50000)\n", "\n", "fig, ax = plt.subplots(figsize=(8, 5.5), dpi=100)\n", "hb = ax.hexbin(x_big, y_big, gridsize=40, cmap='inferno', bins='log', mincnt=1)\n", "\n", "cbar = fig.colorbar(hb, ax=ax)\n", "cbar.set_label(r\"$\\log_{10}(\\text{Sample Density})$\")\n", "\n", "ax.set_title(\"Big Data Density Mapping: Hexbin Tessellation (50,000 pts)\", fontweight='bold')\n", "ax.set_xlabel(\"Latent Feature X\")\n", "ax.set_ylabel(\"Latent Feature Y\")\n", "ax.spines[['top', 'right']].set_visible(False)\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 11: Multi-Attribute Model Competency Radar / Spider Chart\n", "\n", "Compare two AI models across 6 key performance dimensions on a polar coordinate projection:\n", "```python\n", "attributes = ['Speed', 'Accuracy', 'Safety', 'Memory', 'Context', 'Tool Use']\n", "model_a = [90, 85, 70, 60, 95, 80]\n", "model_b = [65, 92, 90, 85, 80, 88]\n", "```\n", "1. Set up a polar Axes with `projection='polar'`.\n", "2. Compute equal radian angles around the $2\\\\pi$ circle and close the polygon loops.\n", "3. Plot both models with distinct colored lines and translucent polygon fills (`alpha=0.2`).\n", "4. Set theta offset to top ($\\\\pi / 2$) and direction clockwise ($-1$).\n", "5. Add attribute labels and a legend.\n" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 11 completed: Multi-attribute polar radar comparison chart\n" ] } ], "source": [ "attributes = ['Speed', 'Accuracy', 'Safety', 'Memory', 'Context', 'Tool Use']\n", "model_a = [90, 85, 70, 60, 95, 80]\n", "model_b = [65, 92, 90, 85, 80, 88]\n", "\n", "n = len(attributes)\n", "angles = np.linspace(0, 2*np.pi, n, endpoint=False).tolist()\n", "angles += angles[:1]\n", "vals_a = model_a + model_a[:1]\n", "vals_b = model_b + model_b[:1]\n", "\n", "fig, ax = plt.subplots(figsize=(6.5, 6), subplot_kw=dict(projection='polar'), dpi=100)\n", "ax.plot(angles, vals_a, color='#2b5c8f', lw=2, label='Model Alpha')\n", "ax.fill(angles, vals_a, color='#2b5c8f', alpha=0.2)\n", "\n", "ax.plot(angles, vals_b, color='#d95f02', lw=2, label='Model Beta')\n", "ax.fill(angles, vals_b, color='#d95f02', alpha=0.2)\n", "\n", "ax.set_theta_offset(np.pi / 2)\n", "ax.set_theta_direction(-1)\n", "ax.set_xticks(angles[:-1])\n", "ax.set_xticklabels(attributes, fontweight='bold', fontsize=9)\n", "ax.set_ylim(0, 100)\n", "ax.set_title(\"AI Model Capability Profiling (Polar Radar Chart)\", fontweight='bold', pad=18)\n", "ax.legend(loc='upper right', bbox_to_anchor=(1.25, 1.1))\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 12: Classifier Calibration Reliability Diagram with Brier Score\n", "\n", "Evaluate whether predicted probabilities correspond to empirical reality:\n", "```python\n", "conf_bins = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])\n", "emp_freq = np.array([0.12, 0.18, 0.33, 0.38, 0.52, 0.58, 0.73, 0.79, 0.91])\n", "```\n", "1. Plot the empirical calibration curve with markers against confidence bins.\n", "2. Plot the perfect calibration reference diagonal line $y = x$ with a dashed black style.\n", "3. Calculate the Brier calibration error: $\\\\frac{1}{N}\\\\sum (\\\\text{emp} - \\\\text{conf})^2$.\n", "4. Display the Brier error score inside the legend label.\n", "5. Set bounds to $[0, 1]$ and format axes as percentages.\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 12 completed: Classifier calibration curve with computed Brier score\n" ] } ], "source": [ "conf_bins = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])\n", "emp_freq = np.array([0.12, 0.18, 0.33, 0.38, 0.52, 0.58, 0.73, 0.79, 0.91])\n", "brier_err = np.mean((emp_freq - conf_bins)**2)\n", "\n", "fig, ax = plt.subplots(figsize=(7, 5), dpi=100)\n", "ax.plot([0, 1], [0, 1], 'k--', lw=1.5, label='Perfect Calibration')\n", "ax.plot(conf_bins, emp_freq, marker='o', color='#2b5c8f', lw=2, markersize=6,\n", " label=f'Classifier (MSE/Brier = {brier_err:.4f})')\n", "\n", "ax.set_title(\"Probability Calibration Reliability Diagram\", fontweight='bold')\n", "ax.set_xlabel(\"Mean Predicted Confidence\")\n", "ax.set_ylabel(\"Empirical True Positive Frequency\")\n", "ax.set_xlim(-0.02, 1.02)\n", "ax.set_ylim(-0.02, 1.02)\n", "ax.grid(True, linestyle=':', alpha=0.5)\n", "ax.legend(loc='upper left', frameon=True)\n", "ax.spines[['top', 'right']].set_visible(False)\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 13: 3D Optimization Surface with Gradient Descent Path\n", "\n", "Visualize optimization over a 2D scalar field:\n", "1. Define a 2D grid over $\\theta_1, \\theta_2 \\\\in [-2, 2]$.\n", "2. Compute loss: $J(\\\\theta_1, \\\\theta_2) = \\\\theta_1^2 + 2\\\\theta_2^2 + \\\\sin(3\\\\theta_1)$.\n", "3. Render a 3D surface plot using `ax.plot_surface()` with `cmap='viridis'`, `alpha=0.8`, and antialiased shading.\n", "4. Overlay a simulated 12-step gradient descent trajectory path in red with circular markers.\n", "5. Set camera elevation to 35 degrees and azimuth to -60 degrees.\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 13 completed: 3D loss surface with optimization trajectory path\n" ] } ], "source": [ "t1 = np.linspace(-2, 2, 80)\n", "t2 = np.linspace(-2, 2, 80)\n", "T1, T2 = np.meshgrid(t1, t2)\n", "J = T1**2 + 2*T2**2 + np.sin(3*T1)\n", "\n", "# Optimization path\n", "steps = 12\n", "p_t1 = np.linspace(1.8, -0.4, steps)\n", "p_t2 = np.linspace(1.5, 0.0, steps)\n", "p_j = p_t1**2 + 2*p_t2**2 + np.sin(3*p_t1)\n", "\n", "fig = plt.figure(figsize=(9, 5.5), dpi=100)\n", "ax = fig.add_subplot(projection='3d')\n", "surf = ax.plot_surface(T1, T2, J, cmap='viridis', alpha=0.8, antialiased=True)\n", "ax.plot(p_t1, p_t2, p_j, color='red', marker='o', lw=2.5, markersize=4, label='GD Trajectory')\n", "\n", "ax.view_init(elev=35, azim=-60)\n", "ax.set_title(r\"3D Optimization Trajectory on $J(\\theta_1, \\theta_2)$\", fontweight='bold')\n", "ax.set_xlabel(r\"$\\theta_1$\")\n", "ax.set_ylabel(r\"$\\theta_2$\")\n", "ax.set_zlabel(\"Cost J\")\n", "ax.legend()\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 14: Dual Coupled Physics Axes with `secondary_xaxis`\n", "\n", "In optics, electromagnetic radiation can be represented either by **Wavelength (nm)** or by **Photon Energy (eV)** via the equation:\n", "$$E = \\\\frac{hc}{\\\\lambda} \\\\approx \\\\frac{1239.84}{\\\\lambda}$$\n", "1. Plot an absorption spectrum curve over wavelength $\\\\lambda \\\\in [400, 900]$ nm.\n", "2. Attach a secondary top X-axis using `ax.secondary_xaxis('top', functions=(forward, inverse))` that displays the corresponding Photon Energy in electron-volts (eV).\n", "3. Label both X-axes with their respective units and styling.\n" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Scenario 14 completed: Dual coupled spectral axes (wavelength nm vs energy eV)\n" ] } ], "source": [ "wavelength_nm = np.linspace(400, 900, 150)\n", "absorption = np.exp(-((wavelength_nm - 550) / 80)**2) + 0.3 * np.exp(-((wavelength_nm - 720) / 50)**2)\n", "\n", "fig, ax = plt.subplots(figsize=(8, 4.5), dpi=100)\n", "ax.plot(wavelength_nm, absorption, color='#2b5c8f', lw=2.2)\n", "ax.set_xlabel(\"Wavelength $\\lambda$ (nm)\", color='#2b5c8f', fontweight='bold')\n", "ax.set_ylabel(\"Optical Absorption (a.u.)\")\n", "\n", "def nm_to_ev(nm):\n", " return 1239.84 / np.maximum(nm, 1e-9)\n", "\n", "def ev_to_nm(ev):\n", " return 1239.84 / np.maximum(ev, 1e-9)\n", "\n", "sec_ax = ax.secondary_xaxis('top', functions=(nm_to_ev, ev_to_nm))\n", "sec_ax.set_xlabel(\"Photon Energy E (eV)\", color='#d95f02', fontweight='bold')\n", "\n", "ax.set_title(\"Optical Absorption Spectrum with Dual Coupled Spectral Axes\", fontweight='bold', pad=15)\n", "ax.grid(True, linestyle=':', alpha=0.5)\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scenario 15: Memory-Safe High-Throughput Batch Figure Generator\n", "\n", "Write a production-grade Python function `batch_plot_pipeline(n_batches=10)` that:\n", "1. Simulates processing 10 successive mini-batches of evaluation data.\n", "2. In each iteration, creates a new Figure, plots batch loss, and saves it to disk as `batch_{i}.png`.\n", "3. Guarantees **zero memory leaks** by explicitly calling `plt.close(fig)` inside a `try...finally` block.\n", "4. Checks and asserts that active Matplotlib figures in memory after the loop is exactly 0.\n", "5. Cleans up the temporary files and prints the total number of successfully exported plots.\n" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Active figures before batch processing: 0\n", "Active figures after batch loop: 0 (Memory fully released!)\n", "Successfully generated, verified, and cleaned 10 batch reports.\n" ] } ], "source": [ "import os\n", "\n", "def batch_plot_pipeline(n_batches=10):\n", " exported_files = []\n", " print(f\"Active figures before batch processing: {len(plt.get_fignums())}\")\n", " \n", " for i in range(n_batches):\n", " fig, ax = plt.subplots(figsize=(4, 2.5), dpi=80)\n", " try:\n", " batch_loss = np.random.uniform(0.1, 0.5, 20)\n", " ax.plot(batch_loss, color='#2b5c8f')\n", " ax.set_title(f\"Batch {i+1} Telemetry\", fontsize=8)\n", " filename = f\"temp_batch_{i+1}.png\"\n", " fig.savefig(filename, bbox_inches='tight')\n", " exported_files.append(filename)\n", " finally:\n", " plt.close(fig) # Immediate memory cleanup!\n", " \n", " active_figs = len(plt.get_fignums())\n", " print(f\"Active figures after batch loop: {active_figs} (Memory fully released!)\")\n", " \n", " # Cleanup temporary files\n", " for fn in exported_files:\n", " if os.path.exists(fn):\n", " os.remove(fn)\n", " \n", " print(f\"Successfully generated, verified, and cleaned {n_batches} batch reports.\")\n", "\n", "batch_plot_pipeline(n_batches=10)\n" ] } ], "metadata": { "kernelspec": { "display_name": "base", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.13.11" } }, "nbformat": 4, "nbformat_minor": 2 }