{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# \ud83d\ude80 Matplotlib Practice Exercise 2: Real-World Scenarios & Advanced Analysis\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": null, "metadata": {}, "outputs": [], "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", "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "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", "\n", "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "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", "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "source": [ "recall = np.linspace(0.01, 1.0, 100)\n", "precision = 1.0 - 0.65 * recall**2\n", "\n", "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "source": [ "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", "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "source": [ "blueprint = [\n", " [\"summary\", \"detail_top\"],\n", " [\"summary\", \"detail_bot\"]\n", "]\n", "\n", "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "source": [ "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "source": [ "days = np.arange(1, 91)\n", "prices = 100 + np.cumsum(np.random.normal(0.2, 1.5, 90))\n", "\n", "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "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", "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "source": [ "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "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", "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "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", "\n", "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "source": [ "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "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", "# Complete scenario solution below\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": null, "metadata": {}, "outputs": [], "source": [ "# Complete scenario solution below\n", "" ] } ], "metadata": { "kernelspec": { "display_name": "base", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.13.11" } }, "nbformat": 4, "nbformat_minor": 2 }