Playbook_data / index.html
Bash06's picture
Upload index.html
fea04bf verified
Raw
History Blame Contribute Delete
182 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ML Data Engineering β€” Master Reference Guide 2026</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=IBM+Plex+Mono:wght@400;500&family=Literata:ital,wght@0,400;0,500;1,400&display=swap');
:root {
--bg: #0a0c10;
--surface: #111318;
--surface2: #191c24;
--border: #252830;
--accent: #4fffb0;
--accent2: #7c6dff;
--accent3: #ff6b6b;
--accent4: #ffd166;
--text: #e8eaf0;
--muted: #7a7f90;
--code-bg: #13161e;
--highlight: rgba(79,255,176,0.08);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: var(--bg);
color: var(--text);
font-family: 'Literata', Georgia, serif;
font-size: 16px;
line-height: 1.75;
display: flex;
min-height: 100vh;
}
/* SIDEBAR */
#sidebar {
width: 280px;
min-width: 280px;
background: var(--surface);
border-right: 1px solid var(--border);
height: 100vh;
position: sticky;
top: 0;
overflow-y: auto;
display: flex;
flex-direction: column;
padding-bottom: 2rem;
}
#sidebar::-webkit-scrollbar { width: 4px; }
#sidebar::-webkit-scrollbar-track { background: transparent; }
#sidebar::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
.sidebar-logo {
padding: 1.5rem 1.2rem 1rem;
border-bottom: 1px solid var(--border);
margin-bottom: 0.5rem;
}
.sidebar-logo h1 {
font-family: 'Syne', sans-serif;
font-weight: 800;
font-size: 1rem;
color: var(--accent);
line-height: 1.2;
letter-spacing: -0.02em;
}
.sidebar-logo p {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.65rem;
color: var(--muted);
margin-top: 0.25rem;
}
.nav-section {
padding: 0.5rem 0;
}
.nav-label {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.6rem;
text-transform: uppercase;
letter-spacing: 0.15em;
color: var(--muted);
padding: 0.6rem 1.2rem 0.3rem;
}
.nav-item {
display: block;
padding: 0.4rem 1.2rem;
color: #9ca3af;
text-decoration: none;
font-family: 'Syne', sans-serif;
font-size: 0.82rem;
font-weight: 500;
border-left: 2px solid transparent;
transition: all 0.15s;
cursor: pointer;
}
.nav-item:hover, .nav-item.active {
color: var(--accent);
border-left-color: var(--accent);
background: var(--highlight);
}
.nav-item .dot {
display: inline-block;
width: 6px;
height: 6px;
border-radius: 50%;
margin-right: 8px;
vertical-align: middle;
background: var(--border);
}
.nav-item:hover .dot, .nav-item.active .dot { background: var(--accent); }
/* MAIN */
#main {
flex: 1;
overflow-y: auto;
padding: 0;
}
#main::-webkit-scrollbar { width: 6px; }
#main::-webkit-scrollbar-track { background: transparent; }
#main::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
.hero {
background: linear-gradient(135deg, #0a0c10 0%, #111320 50%, #0d1018 100%);
padding: 4rem 3rem 3rem;
border-bottom: 1px solid var(--border);
position: relative;
overflow: hidden;
}
.hero::before {
content: '';
position: absolute;
top: -50%;
right: -10%;
width: 500px;
height: 500px;
background: radial-gradient(circle, rgba(79,255,176,0.04) 0%, transparent 70%);
pointer-events: none;
}
.hero-tag {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.7rem;
color: var(--accent);
letter-spacing: 0.2em;
text-transform: uppercase;
margin-bottom: 1rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
.hero-tag::before {
content: '';
display: inline-block;
width: 24px;
height: 1px;
background: var(--accent);
}
.hero h1 {
font-family: 'Syne', sans-serif;
font-weight: 800;
font-size: 2.8rem;
line-height: 1.1;
letter-spacing: -0.04em;
color: var(--text);
margin-bottom: 1rem;
}
.hero h1 span { color: var(--accent); }
.hero p {
color: var(--muted);
font-size: 1rem;
max-width: 600px;
line-height: 1.7;
}
.hero-badges {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin-top: 1.5rem;
}
.badge {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.65rem;
padding: 0.25rem 0.7rem;
border-radius: 100px;
border: 1px solid;
letter-spacing: 0.05em;
}
.badge-green { color: var(--accent); border-color: rgba(79,255,176,0.3); background: rgba(79,255,176,0.05); }
.badge-purple { color: var(--accent2); border-color: rgba(124,109,255,0.3); background: rgba(124,109,255,0.05); }
.badge-red { color: var(--accent3); border-color: rgba(255,107,107,0.3); background: rgba(255,107,107,0.05); }
.badge-yellow { color: var(--accent4); border-color: rgba(255,209,102,0.3); background: rgba(255,209,102,0.05); }
/* SECTIONS */
.section {
padding: 3rem;
border-bottom: 1px solid var(--border);
display: none;
}
.section.active { display: block; }
.section-header {
margin-bottom: 2rem;
}
.section-num {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.65rem;
color: var(--accent);
letter-spacing: 0.2em;
text-transform: uppercase;
margin-bottom: 0.5rem;
}
.section h2 {
font-family: 'Syne', sans-serif;
font-weight: 800;
font-size: 2rem;
letter-spacing: -0.03em;
color: var(--text);
line-height: 1.15;
}
.section h2 .accent { color: var(--accent); }
.section h2 .accent2 { color: var(--accent2); }
.section h2 .accent3 { color: var(--accent3); }
.section h2 .accent4 { color: var(--accent4); }
.section-intro {
margin-top: 1rem;
color: var(--muted);
font-size: 1rem;
max-width: 700px;
line-height: 1.7;
}
h3 {
font-family: 'Syne', sans-serif;
font-weight: 700;
font-size: 1.15rem;
color: var(--text);
margin: 2rem 0 0.75rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
h3::before {
content: '';
display: inline-block;
width: 3px;
height: 1em;
background: var(--accent2);
border-radius: 2px;
flex-shrink: 0;
}
h4 {
font-family: 'Syne', sans-serif;
font-weight: 600;
font-size: 0.95rem;
color: var(--accent4);
margin: 1.5rem 0 0.5rem;
text-transform: uppercase;
letter-spacing: 0.05em;
}
p { margin-bottom: 1rem; line-height: 1.8; color: #c9ccd6; }
ul, ol { padding-left: 1.5rem; margin-bottom: 1rem; }
li { color: #c9ccd6; margin-bottom: 0.4rem; line-height: 1.7; }
li strong { color: var(--text); font-weight: 600; }
/* CODE */
pre {
background: var(--code-bg);
border: 1px solid var(--border);
border-radius: 8px;
padding: 1.25rem 1.5rem;
overflow-x: auto;
margin: 1.25rem 0;
position: relative;
}
pre .code-lang {
position: absolute;
top: 0.5rem;
right: 0.75rem;
font-family: 'IBM Plex Mono', monospace;
font-size: 0.6rem;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.1em;
}
code {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.85rem;
line-height: 1.7;
color: #a8d8b0;
}
p code, li code {
background: var(--code-bg);
border: 1px solid var(--border);
padding: 0.1em 0.4em;
border-radius: 4px;
font-size: 0.82em;
color: var(--accent);
}
.kw { color: #7c6dff; }
.fn { color: #4fffb0; }
.str { color: #ffd166; }
.cm { color: #4a5060; font-style: italic; }
.num { color: #ff6b6b; }
.cls { color: #ff9f7f; }
/* MATH BLOCKS */
.math-block {
background: linear-gradient(135deg, rgba(124,109,255,0.06), rgba(79,255,176,0.04));
border: 1px solid rgba(124,109,255,0.2);
border-left: 3px solid var(--accent2);
border-radius: 8px;
padding: 1.25rem 1.5rem;
margin: 1.25rem 0;
font-family: 'IBM Plex Mono', monospace;
font-size: 0.9rem;
color: #d4b8ff;
line-height: 1.8;
}
.math-block .math-title {
font-size: 0.65rem;
text-transform: uppercase;
letter-spacing: 0.15em;
color: var(--accent2);
margin-bottom: 0.5rem;
}
/* CALLOUTS */
.callout {
border-radius: 8px;
padding: 1rem 1.25rem;
margin: 1.25rem 0;
border-left: 3px solid;
display: flex;
gap: 0.75rem;
}
.callout-icon { font-size: 1.1rem; flex-shrink: 0; margin-top: 0.1rem; }
.callout-body { flex: 1; }
.callout-body p { margin: 0; font-size: 0.9rem; }
.callout-body strong { display: block; margin-bottom: 0.25rem; font-family: 'Syne', sans-serif; font-size: 0.85rem; }
.callout-tip { background: rgba(79,255,176,0.05); border-color: var(--accent); }
.callout-tip .callout-icon, .callout-tip strong { color: var(--accent); }
.callout-warn { background: rgba(255,209,102,0.05); border-color: var(--accent4); }
.callout-warn .callout-icon, .callout-warn strong { color: var(--accent4); }
.callout-danger { background: rgba(255,107,107,0.05); border-color: var(--accent3); }
.callout-danger .callout-icon, .callout-danger strong { color: var(--accent3); }
.callout-info { background: rgba(124,109,255,0.05); border-color: var(--accent2); }
.callout-info .callout-icon, .callout-info strong { color: var(--accent2); }
/* CARDS */
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 1rem;
margin: 1.25rem 0;
}
.card {
background: var(--surface2);
border: 1px solid var(--border);
border-radius: 10px;
padding: 1.25rem;
transition: border-color 0.2s;
}
.card:hover { border-color: var(--accent2); }
.card-icon { font-size: 1.5rem; margin-bottom: 0.75rem; }
.card h5 {
font-family: 'Syne', sans-serif;
font-weight: 700;
font-size: 0.9rem;
color: var(--text);
margin-bottom: 0.4rem;
}
.card p { font-size: 0.8rem; color: var(--muted); margin: 0; line-height: 1.5; }
/* TABLES */
.table-wrap { overflow-x: auto; margin: 1.25rem 0; }
table {
width: 100%;
border-collapse: collapse;
font-size: 0.85rem;
}
thead th {
background: var(--surface2);
color: var(--accent);
font-family: 'IBM Plex Mono', monospace;
font-size: 0.7rem;
text-transform: uppercase;
letter-spacing: 0.1em;
padding: 0.75rem 1rem;
text-align: left;
border-bottom: 1px solid var(--border);
}
tbody td {
padding: 0.75rem 1rem;
border-bottom: 1px solid var(--border);
color: #c9ccd6;
vertical-align: top;
}
tbody tr:hover td { background: var(--highlight); }
.pill {
display: inline-block;
font-family: 'IBM Plex Mono', monospace;
font-size: 0.65rem;
padding: 0.15rem 0.5rem;
border-radius: 100px;
background: rgba(79,255,176,0.1);
color: var(--accent);
border: 1px solid rgba(79,255,176,0.2);
white-space: nowrap;
}
.pill-purple { background: rgba(124,109,255,0.1); color: var(--accent2); border-color: rgba(124,109,255,0.2); }
.pill-red { background: rgba(255,107,107,0.1); color: var(--accent3); border-color: rgba(255,107,107,0.2); }
.pill-yellow { background: rgba(255,209,102,0.1); color: var(--accent4); border-color: rgba(255,209,102,0.2); }
/* PROJECT CARDS */
.project-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 12px;
margin-bottom: 2rem;
overflow: hidden;
}
.project-header {
padding: 1.5rem;
border-bottom: 1px solid var(--border);
display: flex;
align-items: flex-start;
gap: 1rem;
background: var(--surface2);
}
.project-num {
font-family: 'IBM Plex Mono', monospace;
font-size: 2rem;
font-weight: 500;
color: var(--border);
line-height: 1;
flex-shrink: 0;
padding-top: 0.1rem;
}
.project-meta h3 {
font-family: 'Syne', sans-serif;
font-weight: 800;
font-size: 1.3rem;
color: var(--text);
margin: 0 0 0.4rem;
}
.project-meta h3::before { display: none; }
.project-meta p { margin: 0; color: var(--muted); font-size: 0.85rem; }
.project-body { padding: 1.5rem; }
.project-body h4 {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.65rem;
text-transform: uppercase;
letter-spacing: 0.15em;
color: var(--accent2);
margin: 1.25rem 0 0.5rem;
}
.project-body h4:first-child { margin-top: 0; }
.topic-pills { display: flex; flex-wrap: wrap; gap: 0.4rem; margin-bottom: 0.5rem; }
/* INTERVIEW CARDS */
.interview-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 12px;
margin-bottom: 1.5rem;
overflow: hidden;
}
.interview-header {
padding: 1rem 1.5rem;
background: var(--surface2);
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
gap: 0.75rem;
}
.interview-type {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.65rem;
text-transform: uppercase;
letter-spacing: 0.1em;
}
.interview-company {
font-family: 'Syne', sans-serif;
font-weight: 700;
font-size: 0.95rem;
margin-left: auto;
color: var(--muted);
}
.interview-question {
padding: 1.25rem 1.5rem;
font-size: 1rem;
color: var(--text);
font-weight: 500;
font-family: 'Syne', sans-serif;
border-bottom: 1px solid var(--border);
}
.interview-body { padding: 1.25rem 1.5rem; }
.interview-body h5 {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.65rem;
text-transform: uppercase;
letter-spacing: 0.15em;
color: var(--accent4);
margin: 1rem 0 0.4rem;
}
.interview-body h5:first-child { margin-top: 0; }
/* LINKS */
a { color: var(--accent2); text-decoration: none; border-bottom: 1px solid rgba(124,109,255,0.3); }
a:hover { color: var(--accent); border-color: var(--accent); }
.resource-list { list-style: none; padding: 0; }
.resource-list li {
padding: 0.6rem 0;
border-bottom: 1px solid var(--border);
display: flex;
align-items: flex-start;
gap: 0.75rem;
}
.resource-list li::before { content: none; }
.res-type {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.6rem;
padding: 0.15rem 0.5rem;
border-radius: 4px;
flex-shrink: 0;
margin-top: 0.15rem;
}
.res-book { background: rgba(255,107,107,0.1); color: var(--accent3); }
.res-paper { background: rgba(124,109,255,0.1); color: var(--accent2); }
.res-course { background: rgba(79,255,176,0.1); color: var(--accent); }
.res-docs { background: rgba(255,209,102,0.1); color: var(--accent4); }
/* DB COMPARISON */
.db-winner {
background: linear-gradient(135deg, rgba(79,255,176,0.08), rgba(79,255,176,0.02));
border: 1px solid rgba(79,255,176,0.3);
border-radius: 10px;
padding: 1.25rem;
margin: 1rem 0;
}
.db-winner .db-name {
font-family: 'Syne', sans-serif;
font-weight: 800;
font-size: 1.5rem;
color: var(--accent);
margin-bottom: 0.25rem;
}
.db-winner .db-subtitle {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.7rem;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.1em;
}
/* CHECKLIST */
.checklist { list-style: none; padding: 0; }
.checklist li {
padding: 0.4rem 0;
padding-left: 1.75rem;
position: relative;
border-bottom: none;
color: #c9ccd6;
}
.checklist li::before {
content: 'β–‘';
position: absolute;
left: 0;
color: var(--accent);
font-family: 'IBM Plex Mono', monospace;
}
.step-flow {
display: flex;
flex-wrap: wrap;
gap: 0;
margin: 1.25rem 0;
background: var(--surface2);
border: 1px solid var(--border);
border-radius: 8px;
overflow: hidden;
}
.step-item {
flex: 1;
min-width: 120px;
padding: 1rem;
border-right: 1px solid var(--border);
text-align: center;
}
.step-item:last-child { border-right: none; }
.step-item .step-n {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.7rem;
color: var(--accent);
margin-bottom: 0.3rem;
}
.step-item .step-label {
font-family: 'Syne', sans-serif;
font-size: 0.75rem;
font-weight: 600;
color: var(--text);
}
</style>
</head>
<body>
<!-- SIDEBAR -->
<nav id="sidebar">
<div class="sidebar-logo">
<h1>DATA ENGINEERING<br>MASTER GUIDE</h1>
<p>ML Engineer Edition Β· 2026</p>
</div>
<div class="nav-section">
<div class="nav-label">Foundations</div>
<a class="nav-item active" onclick="show('overview')"><span class="dot"></span>Overview</a>
<a class="nav-item" onclick="show('gathering')"><span class="dot"></span>Data Gathering</a>
<a class="nav-item" onclick="show('collection')"><span class="dot"></span>Data Collection</a>
<a class="nav-item" onclick="show('preparation')"><span class="dot"></span>Preparation & Preprocessing</a>
<a class="nav-item" onclick="show('cleaning')"><span class="dot"></span>Cleaning & Manipulation</a>
</div>
<div class="nav-section">
<div class="nav-label">Governance</div>
<a class="nav-item" onclick="show('ethics')"><span class="dot"></span>Data Ethics</a>
<a class="nav-item" onclick="show('governance')"><span class="dot"></span>Governance & Law</a>
<a class="nav-item" onclick="show('dependencies')"><span class="dot"></span>Dependencies & Security</a>
</div>
<div class="nav-section">
<div class="nav-label">Engineering</div>
<a class="nav-item" onclick="show('distributed')"><span class="dot"></span>Distributed Processing</a>
<a class="nav-item" onclick="show('errorhandling')"><span class="dot"></span>Error Handling & Logging</a>
<a class="nav-item" onclick="show('tools')"><span class="dot"></span>Core Tools Deep Dive</a>
<a class="nav-item" onclick="show('scraping')"><span class="dot"></span>Web Scraping</a>
<a class="nav-item" onclick="show('synthetic')"><span class="dot"></span>Synthetic Data & GenAI</a>
</div>
<div class="nav-section">
<div class="nav-label">Infrastructure</div>
<a class="nav-item" onclick="show('databases')"><span class="dot"></span>Database Selection 2026</a>
<a class="nav-item" onclick="show('apache')"><span class="dot"></span>Apache Ecosystem</a>
</div>
<div class="nav-section">
<div class="nav-label">Projects</div>
<a class="nav-item" onclick="show('proj1')"><span class="dot"></span>P1 β€” ETL/Warehousing</a>
<a class="nav-item" onclick="show('proj2')"><span class="dot"></span>P2 β€” EDA & KPI Engine</a>
<a class="nav-item" onclick="show('proj3')"><span class="dot"></span>P3 β€” Capstone</a>
<a class="nav-item" onclick="show('proj4')"><span class="dot"></span>P4 β€” Real-time ML Pipeline</a>
<a class="nav-item" onclick="show('proj5')"><span class="dot"></span>P5 β€” Synthetic Benchmark</a>
</div>
<div class="nav-section">
<div class="nav-label">Interview Prep</div>
<a class="nav-item" onclick="show('interviews')"><span class="dot"></span>Big Tech Questions</a>
<a class="nav-item" onclick="show('resources')"><span class="dot"></span>Books & Papers</a>
</div>
</nav>
<!-- MAIN CONTENT -->
<main id="main">
<!-- HERO / OVERVIEW -->
<div class="hero" id="sec-overview">
<div class="hero-tag">ML Data Engineering</div>
<h1>The <span>Complete</span><br>Data Engineering<br>Playbook</h1>
<p>From raw data to production ML systems β€” covering gathering, preprocessing, ethics, distributed computing, databases, and industry-grade projects with mathematical foundations.</p>
<div class="hero-badges">
<span class="badge badge-green">Python Β· SQL</span>
<span class="badge badge-purple">NumPy Β· Pandas Β· JAX Β· PyTorch Β· TensorFlow</span>
<span class="badge badge-red">Spark Β· Kafka Β· Airflow Β· Snowflake</span>
<span class="badge badge-yellow">PostgreSQL Β· DuckDB Β· MongoDB Β· ChromaDB Β· Neo4j</span>
<span class="badge badge-green">Crawlee Β· Playwright Β· Crawl4AI</span>
<span class="badge badge-purple">GDPR Β· CCPA Β· PDPB Β· Data Sovereignty</span>
</div>
</div>
<div class="section active" id="sec-overview2">
<div class="section-header">
<div class="section-num">00 β€” OVERVIEW</div>
<h2>The <span class="accent">Data Lifecycle</span> for ML Engineers</h2>
<p class="section-intro">Every production ML system is only as good as the data pipeline feeding it. This guide treats the full lifecycle β€” from locating raw sources to serving features in real time β€” as a single interconnected system rather than isolated steps.</p>
</div>
<div class="step-flow">
<div class="step-item"><div class="step-n">01</div><div class="step-label">Gather</div></div>
<div class="step-item"><div class="step-n">02</div><div class="step-label">Collect</div></div>
<div class="step-item"><div class="step-n">03</div><div class="step-label">Prepare</div></div>
<div class="step-item"><div class="step-n">04</div><div class="step-label">Preprocess</div></div>
<div class="step-item"><div class="step-n">05</div><div class="step-label">Clean</div></div>
<div class="step-item"><div class="step-n">06</div><div class="step-label">Manipulate</div></div>
<div class="step-item"><div class="step-n">07</div><div class="step-label">Govern</div></div>
<div class="step-item"><div class="step-n">08</div><div class="step-label">Serve</div></div>
</div>
<p>Think of this pipeline as a <strong>value chain</strong> β€” each stage transforms chaos into signal. The mathematical operations at each step are deterministic; the engineering decisions are where your judgment is tested in interviews and production.</p>
<div class="callout callout-tip">
<div class="callout-icon">πŸ’‘</div>
<div class="callout-body">
<strong>How to Use This Guide</strong>
<p>Navigate using the sidebar. Each section builds on the prior. For interview prep, head to the Interview section directly after reading the Projects. The mathematical formulas are highlighted in purple blocks throughout.</p>
</div>
</div>
<h3>The ML Engineer's Unique Perspective</h3>
<p>Unlike a pure Data Engineer (who optimises for pipeline throughput) or a Data Scientist (who optimises for insight), the ML Engineer optimises for <strong>model-readiness</strong>: the data must be clean enough, feature-rich enough, and reproducibly versioned to train, evaluate, and redeploy models safely in production.</p>
<div class="card-grid">
<div class="card">
<div class="card-icon">🎯</div>
<h5>Feature Quality</h5>
<p>Signal-to-noise ratio in your feature matrix directly determines model performance ceiling.</p>
</div>
<div class="card">
<div class="card-icon">⚑</div>
<h5>Pipeline Velocity</h5>
<p>How fast can you re-train? Your preprocessing must be reproducible, versioned, and fast.</p>
</div>
<div class="card">
<div class="card-icon">πŸ”’</div>
<h5>Legal Safety</h5>
<p>GDPR violations have levied billions in fines. Data governance is a first-class concern.</p>
</div>
<div class="card">
<div class="card-icon">πŸ“ˆ</div>
<h5>Drift Detection</h5>
<p>Models degrade as real-world distributions shift from your training distribution.</p>
</div>
</div>
<h3>Mathematical Formula Quick Reference</h3>
<p>Key formulas are embedded throughout the guide β€” here's a navigational index to find them fast.</p>
<div class="table-wrap">
<table>
<thead><tr><th>Category</th><th>Formula / Concept</th><th>Section</th></tr></thead>
<tbody>
<tr><td><strong>Feature Scaling</strong></td><td>Z-Score: x' = (x βˆ’ ΞΌ) / Οƒ &nbsp;|&nbsp; Min-Max: x' = (x βˆ’ x_min) / (x_max βˆ’ x_min) &nbsp;|&nbsp; Robust: x' = (x βˆ’ Q2) / IQR</td><td>Preparation & Preprocessing</td></tr>
<tr><td><strong>Imputation</strong></td><td>MICE: X_j = f(X_{-j}, ΞΈ_j) β€” iterative chained regression</td><td>Preparation & Preprocessing</td></tr>
<tr><td><strong>Encoding</strong></td><td>Target Encoding: encode(x) = Ξ£y_j / count(x) &nbsp;|&nbsp; Feature Hashing: h(x) = hash(x) mod 2ᡇ</td><td>Preparation & Preprocessing</td></tr>
<tr><td><strong>Dimensionality</strong></td><td>PCA: X = UΞ£Vα΅€, retain Ξ»_k / Σλ β‰₯ 0.95 &nbsp;|&nbsp; t-SNE: min KL(P β€– Q)</td><td>Preparation & Preprocessing</td></tr>
<tr><td><strong>Outlier Detection</strong></td><td>Z-Score: |z| > 3 &nbsp;|&nbsp; IQR Fence: Q1 βˆ’ 1.5Γ—IQR, Q3 + 1.5Γ—IQR &nbsp;|&nbsp; Isolation Forest anomaly score</td><td>Cleaning & Manipulation</td></tr>
<tr><td><strong>Fairness</strong></td><td>Disparate Impact: P(ΕΆ=1|A=min) / P(ΕΆ=1|A=maj) &nbsp;|&nbsp; Equalised Odds &nbsp;|&nbsp; Demographic Parity</td><td>Data Ethics</td></tr>
<tr><td><strong>Privacy</strong></td><td>Ξ΅-DP: P[M(D)∈S] ≀ eα΅‹ Γ— P[M(D')∈S] &nbsp;|&nbsp; Gaussian Mechanism: M(x) = f(x) + N(0, σ²ΔfΒ²)</td><td>Dependencies & Security</td></tr>
<tr><td><strong>Memory</strong></td><td>Memory β‰ˆ rows Γ— cols Γ— bytes_per_dtype &nbsp;|&nbsp; chunk_size = 0.3 Γ— M_avail / bytes_per_row</td><td>Distributed Processing</td></tr>
<tr><td><strong>Broadcasting</strong></td><td>NumPy: dims compatible if equal or one is 1, aligned from right</td><td>Core Tools</td></tr>
<tr><td><strong>Loss Functions</strong></td><td>InfoNCE: βˆ’log[exp(sim(u,i⁺)/Ο„) / Ξ£exp(sim(u,iⱼ⁻)/Ο„)] &nbsp;|&nbsp; CTGAN: min_G max_D</td><td>Projects 4 & 5</td></tr>
<tr><td><strong>Class Imbalance</strong></td><td>SMOTE: x_new = x_i + Ξ»(x_nn βˆ’ x_i) &nbsp;|&nbsp; Cost: argmin_Ο„ [FNΓ—C_fn + FPΓ—C_fp]</td><td>Capstone Project</td></tr>
<tr><td><strong>Evaluation</strong></td><td>E[Cost] = FN Γ— cost_fn + FP Γ— cost_fp &nbsp;|&nbsp; Cramer's V &nbsp;|&nbsp; Point-Biserial r</td><td>Interview Prep</td></tr>
</tbody>
</table>
</div>
</div>
<!-- DATA GATHERING -->
<div class="section" id="sec-gathering">
<div class="section-header">
<div class="section-num">01 β€” GATHERING</div>
<h2>Data <span class="accent">Gathering</span></h2>
<p class="section-intro">Data gathering is the strategic act of identifying where your signal lives. The quality of your dataset ceiling is set here β€” no amount of clever preprocessing can recover information that was never captured.</p>
</div>
<h3>Primary Source Categories</h3>
<div class="table-wrap">
<table>
<thead>
<tr><th>Source Type</th><th>Where to Find</th><th>Quality Signal</th><th>ML Suitability</th></tr>
</thead>
<tbody>
<tr>
<td><strong>Open Government</strong></td>
<td>data.gov, data.europa.eu, data.gov.in, census.gov</td>
<td>High β€” peer-reviewed collection methods</td>
<td><span class="pill">Tabular / TS</span></td>
</tr>
<tr>
<td><strong>Academic Repositories</strong></td>
<td>UCI ML Repository, Harvard Dataverse, OpenML, Zenodo</td>
<td>Very High β€” curated, benchmarked</td>
<td><span class="pill">All types</span></td>
</tr>
<tr>
<td><strong>Platform APIs</strong></td>
<td>Twitter/X API, Reddit Pushshift, GitHub GraphQL, Wikipedia API</td>
<td>Medium β€” rate-limited, terms-restricted</td>
<td><span class="pill">NLP / Social</span></td>
</tr>
<tr>
<td><strong>Financial Markets</strong></td>
<td>Yahoo Finance, Alpha Vantage, Quandl, FRED (St. Louis Fed)</td>
<td>High β€” standardised OHLCV</td>
<td><span class="pill">Time Series</span></td>
</tr>
<tr>
<td><strong>IoT / Sensor</strong></td>
<td>Kaggle, NASA EarthData, NOAA, OpenAQ</td>
<td>Varies β€” check calibration metadata</td>
<td><span class="pill">Streaming / TS</span></td>
</tr>
<tr>
<td><strong>Synthetic / Simulated</strong></td>
<td>SDV, Gretel.ai, CTGAN, Faker, DiffPrivLib</td>
<td>Controlled β€” distribution assumptions matter</td>
<td><span class="pill">All types</span></td>
</tr>
<tr>
<td><strong>Web Scraping</strong></td>
<td>Crawlee, Playwright, Scrapy, Crawl4AI</td>
<td>Low-Medium β€” brittle, legal risk</td>
<td><span class="pill">NLP / Vision</span></td>
</tr>
<tr>
<td><strong>Crowd-sourced</strong></td>
<td>Mechanical Turk, Scale.ai, Label Studio</td>
<td>Medium β€” inter-annotator agreement critical</td>
<td><span class="pill">Supervised</span></td>
</tr>
</tbody>
</table>
</div>
<h3>Key Repositories for ML</h3>
<ul>
<li><strong>Kaggle Datasets</strong> β€” <code>kaggle.com/datasets</code> β€” Community-driven, versioned, competition-tested</li>
<li><strong>Hugging Face Hub</strong> β€” <code>huggingface.co/datasets</code> β€” Best for NLP, multimodal; use <code>datasets</code> library</li>
<li><strong>TensorFlow Datasets (TFDS)</strong> β€” Standardised pipelines for CV/NLP benchmarks</li>
<li><strong>Paperswithcode Datasets</strong> β€” Tied to reproducible research benchmarks</li>
<li><strong>AWS Open Data Registry</strong> β€” Petabyte-scale scientific datasets on S3</li>
<li><strong>Google Dataset Search</strong> β€” <code>datasetsearch.research.google.com</code></li>
<li><strong>OpenStreetMap / Overpass API</strong> β€” Geospatial ground truth</li>
</ul>
<h3>Data Gathering Strategy Framework</h3>
<div class="callout callout-info">
<div class="callout-icon">🧭</div>
<div class="callout-body">
<strong>The 5V Assessment</strong>
<p>Before committing to a source, evaluate: <strong>Volume</strong> (enough examples per class?), <strong>Velocity</strong> (can you keep up with updates?), <strong>Variety</strong> (format diversity vs. homogeneity?), <strong>Veracity</strong> (labelling trustworthiness, provenance), and <strong>Value</strong> (does this source add marginal lift to your model?).</p>
</div>
</div>
<pre><code><span class="cm"># Programmatic dataset acquisition with Hugging Face</span>
<span class="kw">from</span> datasets <span class="kw">import</span> load_dataset
<span class="kw">import</span> pandas <span class="kw">as</span> pd
<span class="cm"># Load a specific split and cache locally</span>
ds = load_dataset(<span class="str">"imdb"</span>, split=<span class="str">"train"</span>, cache_dir=<span class="str">"./data_cache"</span>)
<span class="cm"># Convert to Pandas for exploration</span>
df = ds.to_pandas()
<span class="fn">print</span>(df.dtypes)
<span class="fn">print</span>(df.describe(include=<span class="str">'all'</span>))
<span class="cm"># For Kaggle API</span>
<span class="cm"># pip install kaggle</span>
<span class="cm"># Set KAGGLE_USERNAME and KAGGLE_KEY env variables</span>
<span class="kw">import</span> subprocess
subprocess.<span class="fn">run</span>([<span class="str">"kaggle"</span>, <span class="str">"datasets"</span>, <span class="str">"download"</span>,
<span class="str">"-d"</span>, <span class="str">"username/dataset-name"</span>,
<span class="str">"--unzip"</span>, <span class="str">"-p"</span>, <span class="str">"./data"</span>])
<div class="code-lang">python</div></code></pre>
<h3>Data Lineage Tracking</h3>
<p>Every dataset you gather should have a <strong>lineage record</strong> β€” a machine-readable provenance log documenting source URL, access date, licence, version hash, and the transformation chain applied. Tools like <strong>Apache Atlas</strong>, <strong>DataHub</strong>, and <strong>MLflow</strong> (for experiment context) help automate this.</p>
<pre><code><span class="cm"># Simple lineage metadata pattern</span>
<span class="kw">import</span> json, hashlib
<span class="kw">from</span> datetime <span class="kw">import</span> datetime
<span class="kw">def</span> <span class="fn">record_lineage</span>(source_url: str, local_path: str, licence: str) -> dict:
<span class="kw">with</span> <span class="fn">open</span>(local_path, <span class="str">"rb"</span>) <span class="kw">as</span> f:
sha256 = hashlib.<span class="fn">sha256</span>(f.<span class="fn">read</span>()).<span class="fn">hexdigest</span>()
record = {
<span class="str">"source"</span>: source_url,
<span class="str">"local_path"</span>: local_path,
<span class="str">"accessed_at"</span>: datetime.<span class="fn">utcnow</span>().<span class="fn">isoformat</span>(),
<span class="str">"sha256"</span>: sha256,
<span class="str">"licence"</span>: licence,
<span class="str">"transformations"</span>: []
}
<span class="kw">with</span> <span class="fn">open</span>(<span class="str">"lineage.json"</span>, <span class="str">"a"</span>) <span class="kw">as</span> f:
f.<span class="fn">write</span>(json.<span class="fn">dumps</span>(record) + <span class="str">"\n"</span>)
<span class="kw">return</span> record
<div class="code-lang">python</div></code></pre>
</div>
<!-- DATA COLLECTION -->
<div class="section" id="sec-collection">
<div class="section-header">
<div class="section-num">02 β€” COLLECTION</div>
<h2>Data <span class="accent2">Collection</span></h2>
<p class="section-intro">Collection is the execution layer β€” the infrastructure, protocols, and formats that move raw data from source into your control. Good collection architecture is idempotent, resumable, and schema-aware.</p>
</div>
<h3>Structuring Your Collection Architecture</h3>
<p>A well-designed collection pipeline has three tiers: an <strong>ingestion layer</strong> (APIs, scrapers, streams), a <strong>landing zone</strong> (raw, immutable storage β€” think S3 or GCS), and a <strong>staging area</strong> (where format normalisation happens before the warehouse). Never write raw data directly to a transformed table.</p>
<div class="step-flow">
<div class="step-item"><div class="step-n">Ingest</div><div class="step-label">API / Stream / Scrape</div></div>
<div class="step-item"><div class="step-n">Land</div><div class="step-label">Raw Storage (S3/GCS)</div></div>
<div class="step-item"><div class="step-n">Stage</div><div class="step-label">Schema Normalise</div></div>
<div class="step-item"><div class="step-n">Validate</div><div class="step-label">Great Expectations</div></div>
<div class="step-item"><div class="step-n">Load</div><div class="step-label">Warehouse / Lake</div></div>
</div>
<h3>File Format Selection</h3>
<div class="table-wrap">
<table>
<thead>
<tr><th>Format</th><th>Best For</th><th>Columnar?</th><th>Compression</th><th>Schema Evolution</th></tr>
</thead>
<tbody>
<tr><td><strong>Parquet</strong></td><td>Analytical workloads, feature stores</td><td>βœ…</td><td>Excellent (Snappy/ZSTD)</td><td>Limited</td></tr>
<tr><td><strong>Arrow / Feather</strong></td><td>In-memory IPC, Pandas ↔ Spark</td><td>βœ…</td><td>Good (LZ4)</td><td>Good</td></tr>
<tr><td><strong>Delta Lake</strong></td><td>ACID transactions on data lakes</td><td>βœ… (Parquet under)</td><td>Excellent</td><td>Excellent</td></tr>
<tr><td><strong>JSON Lines (JSONL)</strong></td><td>Semi-structured, NLP corpora</td><td>❌</td><td>Poor raw / Good gzip</td><td>Excellent</td></tr>
<tr><td><strong>CSV</strong></td><td>Interchange only β€” avoid at scale</td><td>❌</td><td>Poor</td><td>None</td></tr>
<tr><td><strong>HDF5 / Zarr</strong></td><td>Numerical arrays, geospatial rasters</td><td>❌</td><td>Good</td><td>None</td></tr>
<tr><td><strong>TFRecord</strong></td><td>TensorFlow training pipelines</td><td>❌</td><td>Good</td><td>Protobuf-based</td></tr>
</tbody>
</table>
</div>
<div class="callout callout-tip">
<div class="callout-icon">πŸ’‘</div>
<div class="callout-body">
<strong>Rule of thumb for ML</strong>
<p>Use <strong>Parquet</strong> as your analytical format, <strong>Arrow</strong> as your in-memory interchange format, and <strong>Delta Lake</strong> when you need ACID guarantees (versioning, upserts) on your feature store.</p>
</div>
</div>
<h3>API Collection Pattern (REST & GraphQL)</h3>
<pre><code><span class="kw">import</span> httpx, time, json
<span class="kw">from</span> tenacity <span class="kw">import</span> retry, stop_after_attempt, wait_exponential
<span class="cls">@retry</span>(stop=<span class="fn">stop_after_attempt</span>(<span class="num">5</span>),
wait=<span class="fn">wait_exponential</span>(multiplier=<span class="num">1</span>, min=<span class="num">2</span>, max=<span class="num">60</span>))
<span class="kw">async def</span> <span class="fn">fetch_paginated</span>(url: str, headers: dict, params: dict) -> list:
<span class="str">"""
Robust paginated API collection with exponential backoff.
Handles rate-limiting (HTTP 429) gracefully.
"""</span>
results = []
<span class="kw">async with</span> httpx.<span class="fn">AsyncClient</span>(timeout=<span class="num">30.0</span>) <span class="kw">as</span> client:
<span class="kw">while</span> url:
resp = <span class="kw">await</span> client.<span class="fn">get</span>(url, headers=headers, params=params)
<span class="kw">if</span> resp.status_code == <span class="num">429</span>:
retry_after = <span class="fn">int</span>(resp.headers.<span class="fn">get</span>(<span class="str">"Retry-After"</span>, <span class="num">60</span>))
time.<span class="fn">sleep</span>(retry_after)
<span class="kw">continue</span>
resp.<span class="fn">raise_for_status</span>()
data = resp.<span class="fn">json</span>()
results.<span class="fn">extend</span>(data.<span class="fn">get</span>(<span class="str">"items"</span>, []))
url = data.<span class="fn">get</span>(<span class="str">"next_page_url"</span>) <span class="cm"># pagination cursor</span>
params = {} <span class="cm"># cursor already encoded in next_page_url</span>
<span class="kw">return</span> results
<div class="code-lang">python</div></code></pre>
<h3>Schema Validation with Great Expectations</h3>
<pre><code><span class="kw">import</span> great_expectations <span class="kw">as</span> gx
context = gx.<span class="fn">get_context</span>()
ds = context.<span class="fn">sources</span>.<span class="fn">add_pandas</span>(<span class="str">"my_source"</span>)
da = ds.<span class="fn">add_dataframe_asset</span>(<span class="str">"users"</span>)
batch = da.<span class="fn">build_batch_request</span>()
suite = context.<span class="fn">add_expectation_suite</span>(<span class="str">"users_suite"</span>)
validator = context.<span class="fn">get_validator</span>(batch_request=batch,
expectation_suite_name=<span class="str">"users_suite"</span>)
<span class="cm"># Define schema contract</span>
validator.<span class="fn">expect_column_to_exist</span>(<span class="str">"user_id"</span>)
validator.<span class="fn">expect_column_values_to_not_be_null</span>(<span class="str">"user_id"</span>)
validator.<span class="fn">expect_column_values_to_be_unique</span>(<span class="str">"user_id"</span>)
validator.<span class="fn">expect_column_values_to_be_between</span>(<span class="str">"age"</span>, min_value=<span class="num">0</span>, max_value=<span class="num">120</span>)
validator.<span class="fn">expect_column_values_to_match_regex</span>(<span class="str">"email"</span>, <span class="str">r"^[^@]+@[^@]+\.[^@]+$"</span>)
results = validator.<span class="fn">validate</span>()
<span class="fn">assert</span> results.success, <span class="str">"Schema validation FAILED β€” pipeline halted."</span>
<div class="code-lang">python</div></code></pre>
</div>
<!-- PREPARATION & PREPROCESSING -->
<div class="section" id="sec-preparation">
<div class="section-header">
<div class="section-num">03 & 04 β€” PREPARATION & PREPROCESSING</div>
<h2>Preparation <span class="accent">&</span> <span class="accent2">Preprocessing</span></h2>
<p class="section-intro">Preparation is structural organisation; preprocessing is numerical transformation. Together they convert raw tables into a feature matrix a model can learn from. The mathematical operations here directly control what the model can and cannot learn.</p>
</div>
<h3>Preparation: Sorting and Arranging</h3>
<p>At this stage you perform <strong>schema alignment</strong> (unifying column names and types across sources), <strong>join strategy selection</strong> (star vs. snowflake schemas), and <strong>train/val/test split design</strong>. The order matters β€” you must design splits <em>before</em> any preprocessing that uses statistics from the data (like mean imputation), otherwise you leak test-set statistics into your training pipeline.</p>
<div class="callout callout-danger">
<div class="callout-icon">⚠️</div>
<div class="callout-body">
<strong>Data Leakage β€” The Most Common Pipeline Bug</strong>
<p>Never compute scaling parameters, imputation values, or encoding mappings using the entire dataset before splitting. Always fit transformations on training data only, then apply (transform) to validation and test. Using a <code>Pipeline</code> object in scikit-learn enforces this automatically.</p>
</div>
</div>
<pre><code><span class="kw">from</span> sklearn.pipeline <span class="kw">import</span> Pipeline
<span class="kw">from</span> sklearn.preprocessing <span class="kw">import</span> StandardScaler, OneHotEncoder
<span class="kw">from</span> sklearn.impute <span class="kw">import</span> SimpleImputer
<span class="kw">from</span> sklearn.compose <span class="kw">import</span> ColumnTransformer
<span class="kw">from</span> sklearn.model_selection <span class="kw">import</span> train_test_split
<span class="cm"># Split FIRST</span>
X_train, X_test, y_train, y_test = <span class="fn">train_test_split</span>(
X, y, test_size=<span class="num">0.2</span>, random_state=<span class="num">42</span>, stratify=y
)
numeric_pipe = <span class="fn">Pipeline</span>([
(<span class="str">"imputer"</span>, <span class="fn">SimpleImputer</span>(strategy=<span class="str">"median"</span>)),
(<span class="str">"scaler"</span>, <span class="fn">StandardScaler</span>())
])
cat_pipe = <span class="fn">Pipeline</span>([
(<span class="str">"imputer"</span>, <span class="fn">SimpleImputer</span>(strategy=<span class="str">"most_frequent"</span>)),
(<span class="str">"encoder"</span>, <span class="fn">OneHotEncoder</span>(handle_unknown=<span class="str">"ignore"</span>, sparse_output=<span class="kw">False</span>))
])
preprocessor = <span class="fn">ColumnTransformer</span>([
(<span class="str">"num"</span>, numeric_pipe, numeric_cols),
(<span class="str">"cat"</span>, cat_pipe, categorical_cols)
])
<span class="cm"># FIT on train only β€” TRANSFORM both</span>
preprocessor.<span class="fn">fit</span>(X_train)
X_train_processed = preprocessor.<span class="fn">transform</span>(X_train)
X_test_processed = preprocessor.<span class="fn">transform</span>(X_test)
<div class="code-lang">python</div></code></pre>
<h3>Core Preprocessing Operations with Mathematical Intuition</h3>
<h4>1. Feature Scaling</h4>
<p>Neural networks, SVMs, and K-Means are scale-sensitive. Tree-based models (XGBoost, Random Forest) are scale-invariant. Always understand your algorithm before scaling.</p>
<div class="math-block">
<div class="math-title">Z-Score Normalisation (StandardScaler)</div>
x' = (x βˆ’ ΞΌ) / Οƒ<br>
where ΞΌ = mean, Οƒ = standard deviation<br>
Result: zero mean, unit variance. Good for Gaussian-distributed data.<br><br>
<div class="math-title">Min-Max Scaling</div>
x' = (x βˆ’ x_min) / (x_max βˆ’ x_min) β†’ result ∈ [0, 1]<br>
Sensitive to outliers. Use RobustScaler (IQR-based) if outliers present.<br><br>
<div class="math-title">RobustScaler (IQR)</div>
x' = (x βˆ’ Q2) / (Q3 βˆ’ Q1)<br>
Q2 = median, Q1/Q3 = 25th/75th percentiles. Outlier-resistant.
</div>
<h4>2. Missing Value Strategies</h4>
<div class="table-wrap">
<table>
<thead><tr><th>Mechanism</th><th>Definition</th><th>Best Strategy</th></tr></thead>
<tbody>
<tr><td><strong>MCAR</strong></td><td>Missing Completely At Random</td><td>Mean/median imputation, row deletion</td></tr>
<tr><td><strong>MAR</strong></td><td>Missing At Random (conditional on other cols)</td><td>KNN imputation, iterative imputer (MICE)</td></tr>
<tr><td><strong>MNAR</strong></td><td>Missing Not At Random (value depends on itself)</td><td>Add missingness indicator flag + model-based imputation</td></tr>
</tbody>
</table>
</div>
<div class="math-block">
<div class="math-title">MICE β€” Multiple Imputation by Chained Equations</div>
For each feature j with missing values:<br>
X_j = f(X_{-j}, ΞΈ_j) where X_{-j} are all other features<br>
Fit a model for each feature, iteratively impute until convergence.<br>
In sklearn: IterativeImputer (experimental) with BayesianRidge estimator.
</div>
<pre><code><span class="kw">from</span> sklearn.experimental <span class="kw">import</span> enable_iterative_imputer <span class="cm"># noqa</span>
<span class="kw">from</span> sklearn.impute <span class="kw">import</span> IterativeImputer
<span class="kw">from</span> sklearn.linear_model <span class="kw">import</span> BayesianRidge
<span class="kw">import</span> numpy <span class="kw">as</span> np
imputer = <span class="fn">IterativeImputer</span>(
estimator=<span class="fn">BayesianRidge</span>(),
n_nearest_features=<span class="num">5</span>, <span class="cm"># use 5 most correlated features</span>
max_iter=<span class="num">10</span>,
random_state=<span class="num">42</span>,
tol=<span class="num">1e-3</span>
)
X_imputed = imputer.<span class="fn">fit_transform</span>(X_train) <span class="cm"># fit on train only!</span>
<div class="code-lang">python</div></code></pre>
<h4>3. Encoding Categorical Variables</h4>
<div class="math-block">
<div class="math-title">Target Encoding (Mean Encoding)</div>
encode(x_i) = (Ξ£ y_j for all j where X_j = x_i) / count(x_i = x_i)<br>
Risk: target leakage on training set. Use cross-fold target encoding to prevent this.<br><br>
<div class="math-title">Ordinal Hashing (Feature Hashing)</div>
h(x) = hash(x) mod 2^b β†’ sparse matrix of width 2^b<br>
Useful for very high-cardinality categoricals (e.g., user IDs with millions of values).
</div>
<h4>4. Feature Engineering: Interaction Terms &amp; Polynomial Features</h4>
<div class="math-block">
<div class="math-title">Polynomial Feature Expansion</div>
For features [x₁, xβ‚‚] with degree=2:<br>
Output: [1, x₁, xβ‚‚, x₁², x₁xβ‚‚, xβ‚‚Β²]<br>
Number of features: C(n + d, d) where n = original features, d = degree<br>
Risk: combinatorial explosion. Use SelectFromModel (Lasso) to prune.
</div>
<h4>5. Dimensionality Reduction</h4>
<div class="math-block">
<div class="math-title">Principal Component Analysis (PCA)</div>
Decompose data matrix X (nΓ—p) as: X = UΞ£Vα΅€ (SVD)<br>
Principal components: Z = XV (project onto eigenvectors)<br>
Explained variance ratio: Ξ»_k / Σλ_i where Ξ» are eigenvalues of Xα΅€X<br>
Rule of thumb: retain components explaining 95% of cumulative variance.<br><br>
<div class="math-title">t-SNE (Barnes-Hut)</div>
Minimise KL(P || Q) where P is high-dim joint distribution, Q is low-dim<br>
P(j|i) = exp(βˆ’β€–x_i βˆ’ x_jβ€–Β² / 2Οƒ_iΒ²) / Ξ£_{kβ‰ i} exp(βˆ’β€–x_i βˆ’ x_kβ€–Β² / 2Οƒ_iΒ²)<br>
Perplexity (5–50) controls effective neighbourhood size. Not for &gt;50k samples.
</div>
<pre><code><span class="kw">import</span> numpy <span class="kw">as</span> np
<span class="kw">from</span> sklearn.decomposition <span class="kw">import</span> PCA
<span class="kw">import</span> matplotlib.pyplot <span class="kw">as</span> plt
<span class="cm"># Determine optimal n_components</span>
pca_full = <span class="fn">PCA</span>().<span class="fn">fit</span>(X_train_scaled)
cumvar = np.<span class="fn">cumsum</span>(pca_full.explained_variance_ratio_)
n_components = np.<span class="fn">argmax</span>(cumvar >= <span class="num">0.95</span>) + <span class="num">1</span>
<span class="fn">print</span>(<span class="str">f"Components for 95% variance: {n_components}"</span>)
pca = <span class="fn">PCA</span>(n_components=n_components, random_state=<span class="num">42</span>)
X_reduced = pca.<span class="fn">fit_transform</span>(X_train_scaled)
<div class="code-lang">python</div></code></pre>
</div>
<!-- CLEANING & MANIPULATION -->
<div class="section" id="sec-cleaning">
<div class="section-header">
<div class="section-num">05 & 06 β€” CLEANING & MANIPULATION</div>
<h2>Cleaning <span class="accent3">&amp;</span> Manipulation</h2>
<p class="section-intro">Data cleaning removes noise; manipulation reshapes the signal. Both require decisions guided by domain knowledge, statistical tests, and an understanding of downstream model sensitivity.</p>
</div>
<h3>Outlier Detection Methods</h3>
<div class="math-block">
<div class="math-title">Z-Score Method</div>
outlier if |z_i| &gt; 3 where z_i = (x_i βˆ’ ΞΌ) / Οƒ<br>
Assumes Gaussian distribution. Fails for heavy-tailed distributions.<br><br>
<div class="math-title">IQR Fence Method (Tukey)</div>
Lower fence = Q1 βˆ’ 1.5 Γ— IQR<br>
Upper fence = Q3 + 1.5 Γ— IQR<br>
where IQR = Q3 βˆ’ Q1 (25th to 75th percentile range)<br><br>
<div class="math-title">Isolation Forest</div>
Anomaly score = 2^(βˆ’E[h(x)] / c(n))<br>
where h(x) = path length to isolate x, c(n) = 2H(n-1) βˆ’ 2(n-1)/n (expected path length)<br>
Scores near 1 indicate anomalies; scores near 0.5 indicate normal points.
</div>
<pre><code><span class="kw">import</span> pandas <span class="kw">as</span> pd
<span class="kw">import</span> numpy <span class="kw">as</span> np
<span class="kw">from</span> sklearn.ensemble <span class="kw">import</span> IsolationForest
<span class="kw">def</span> <span class="fn">comprehensive_outlier_report</span>(df: pd.DataFrame, numeric_cols: list) -> pd.DataFrame:
report = pd.<span class="fn">DataFrame</span>(index=numeric_cols)
<span class="cm"># Z-Score outliers</span>
z = (df[numeric_cols] - df[numeric_cols].<span class="fn">mean</span>()) / df[numeric_cols].<span class="fn">std</span>()
report[<span class="str">"zscore_outliers"</span>] = (z.<span class="fn">abs</span>() > <span class="num">3</span>).<span class="fn">sum</span>()
<span class="cm"># IQR outliers</span>
Q1 = df[numeric_cols].<span class="fn">quantile</span>(<span class="num">0.25</span>)
Q3 = df[numeric_cols].<span class="fn">quantile</span>(<span class="num">0.75</span>)
IQR = Q3 - Q1
iqr_mask = (df[numeric_cols] < (Q1 - <span class="num">1.5</span>*IQR)) | (df[numeric_cols] > (Q3 + <span class="num">1.5</span>*IQR))
report[<span class="str">"iqr_outliers"</span>] = iqr_mask.<span class="fn">sum</span>()
<span class="kw">return</span> report
<span class="cm"># Isolation Forest for multivariate anomaly detection</span>
iso = <span class="fn">IsolationForest</span>(contamination=<span class="num">0.05</span>, random_state=<span class="num">42</span>, n_jobs=-<span class="num">1</span>)
outlier_labels = iso.<span class="fn">fit_predict</span>(X_numeric) <span class="cm"># -1 = anomaly, 1 = normal</span>
df_clean = df[outlier_labels == <span class="num">1</span>]
<span class="fn">print</span>(<span class="str">f"Removed {(outlier_labels == -1).sum()} anomalies ({(outlier_labels == -1).mean():.1%})"</span>)
<div class="code-lang">python</div></code></pre>
<h3>Duplicate Detection</h3>
<pre><code><span class="cm"># Exact duplicates</span>
exact_dupes = df.<span class="fn">duplicated</span>(keep=<span class="str">"first"</span>)
df = df[~exact_dupes]
<span class="cm"># Fuzzy deduplication (near-duplicates in text)</span>
<span class="kw">from</span> datasketch <span class="kw">import</span> MinHash, MinHashLSH
<span class="kw">def</span> <span class="fn">minhash_dedup</span>(texts: list, threshold: float = <span class="num">0.8</span>) -> list:
<span class="str">"""MinHash LSH for approximate deduplication β€” O(n) vs O(nΒ²)"""</span>
lsh = <span class="fn">MinHashLSH</span>(threshold=threshold, num_perm=<span class="num">128</span>)
minhashes = {}
keep_indices = []
<span class="kw">for</span> i, text <span class="kw">in</span> <span class="fn">enumerate</span>(texts):
m = <span class="fn">MinHash</span>(num_perm=<span class="num">128</span>)
<span class="kw">for</span> word <span class="kw">in</span> text.<span class="fn">lower</span>().<span class="fn">split</span>():
m.<span class="fn">update</span>(word.<span class="fn">encode</span>(<span class="str">"utf8"</span>))
<span class="kw">if</span> <span class="kw">not</span> lsh.<span class="fn">query</span>(m): <span class="cm"># no similar doc found</span>
lsh.<span class="fn">insert</span>(<span class="str">f"doc_{i}"</span>, m)
keep_indices.<span class="fn">append</span>(i)
<span class="kw">return</span> keep_indices
<div class="code-lang">python</div></code></pre>
<h3>Data Manipulation Best Practices</h3>
<h4>Pandas β€” Production Patterns</h4>
<pre><code><span class="kw">import</span> pandas <span class="kw">as</span> pd
<span class="kw">import</span> numpy <span class="kw">as</span> np
<span class="cm"># Use vectorised operations β€” NEVER iterate rows</span>
df[<span class="str">"revenue_log"</span>] = np.<span class="fn">log1p</span>(df[<span class="str">"revenue"</span>]) <span class="cm"># log(1+x) handles zeros</span>
<span class="cm"># Downcasting dtypes saves 60-80% memory</span>
<span class="kw">def</span> <span class="fn">reduce_memory</span>(df):
<span class="kw">for</span> col <span class="kw">in</span> df.<span class="fn">select_dtypes</span>(include=[<span class="str">"float64"</span>]).columns:
df[col] = pd.<span class="fn">to_numeric</span>(df[col], downcast=<span class="str">"float"</span>)
<span class="kw">for</span> col <span class="kw">in</span> df.<span class="fn">select_dtypes</span>(include=[<span class="str">"int64"</span>]).columns:
df[col] = pd.<span class="fn">to_numeric</span>(df[col], downcast=<span class="str">"integer"</span>)
<span class="kw">for</span> col <span class="kw">in</span> df.<span class="fn">select_dtypes</span>(include=[<span class="str">"object"</span>]).columns:
<span class="kw">if</span> df[col].<span class="fn">nunique</span>() / <span class="fn">len</span>(df) < <span class="num">0.05</span>: <span class="cm"># &lt;5% unique = categorical</span>
df[col] = df[col].<span class="fn">astype</span>(<span class="str">"category"</span>)
<span class="kw">return</span> df
<span class="cm"># Window functions for time-series features</span>
df = df.<span class="fn">sort_values</span>([<span class="str">"user_id"</span>, <span class="str">"timestamp"</span>])
df[<span class="str">"rolling_7d_avg"</span>] = (
df.<span class="fn">groupby</span>(<span class="str">"user_id"</span>)[<span class="str">"value"</span>]
.<span class="fn">transform</span>(<span class="kw">lambda</span> x: x.<span class="fn">rolling</span>(<span class="num">7</span>, min_periods=<span class="num">1</span>).<span class="fn">mean</span>())
)
<span class="cm"># Efficient merge strategy</span>
df_merged = df_left.<span class="fn">merge</span>(
df_right,
on=<span class="str">"id"</span>,
how=<span class="str">"left"</span>,
validate=<span class="str">"m:1"</span> <span class="cm"># asserts join cardinality β€” catches duplicates</span>
)
<div class="code-lang">python</div></code></pre>
<h4>SQL Manipulation (PostgreSQL / DuckDB)</h4>
<pre><code><span class="cm">-- Window function: rolling 30-day revenue per user</span>
<span class="kw">SELECT</span>
user_id,
event_date,
revenue,
<span class="fn">SUM</span>(revenue) <span class="kw">OVER</span> (
<span class="kw">PARTITION BY</span> user_id
<span class="kw">ORDER BY</span> event_date
<span class="kw">ROWS BETWEEN</span> <span class="num">29</span> <span class="kw">PRECEDING AND CURRENT ROW</span>
) <span class="kw">AS</span> rolling_30d_revenue,
<span class="cm">-- Percentile rank within cohort</span>
<span class="fn">PERCENT_RANK</span>() <span class="kw">OVER</span> (<span class="kw">PARTITION BY</span> cohort_month <span class="kw">ORDER BY</span> revenue) <span class="kw">AS</span> pct_rank,
<span class="cm">-- Lag features for churn modelling</span>
<span class="fn">LAG</span>(revenue, <span class="num">1</span>) <span class="kw">OVER</span> (<span class="kw">PARTITION BY</span> user_id <span class="kw">ORDER BY</span> event_date) <span class="kw">AS</span> prev_revenue,
revenue - <span class="fn">LAG</span>(revenue, <span class="num">1</span>) <span class="kw">OVER</span> (<span class="kw">PARTITION BY</span> user_id <span class="kw">ORDER BY</span> event_date) <span class="kw">AS</span> mom_delta
<span class="kw">FROM</span> transactions;
<div class="code-lang">sql</div></code></pre>
</div>
<!-- ETHICS -->
<div class="section" id="sec-ethics">
<div class="section-header">
<div class="section-num">07 β€” ETHICS</div>
<h2>Data <span class="accent4">Ethics</span></h2>
<p class="section-intro">Data ethics is not a soft concern β€” it is a technical, legal, and reputational risk layer. Bias baked into training data propagates through every model prediction at scale.</p>
</div>
<h3>The Ethics Checklist (Before Any Dataset Publication)</h3>
<ul class="checklist">
<li>Informed consent: was data collected with explicit user knowledge and agreement?</li>
<li>Purpose limitation: are you using data only for the stated purpose?</li>
<li>Data minimisation: have you collected the minimum data sufficient for the task?</li>
<li>Anonymisation / pseudonymisation: are PII fields removed or hashed?</li>
<li>Re-identification risk: is the combination of fields enough to re-identify individuals?</li>
<li>Demographic representation: does your dataset reflect the population the model serves?</li>
<li>Labelling fairness: were annotators from diverse backgrounds? Check inter-annotator agreement.</li>
<li>Historical bias: does your target variable encode historical discrimination (e.g., loan defaults shaped by redlining)?</li>
<li>Right to erasure: can you delete a user's data from the training set and retrain?</li>
<li>Transparency: is the dataset documented with a Datasheet (Gebru et al. 2018) or Data Nutrition Label?</li>
</ul>
<h3>Bias Detection β€” Mathematical Framework</h3>
<div class="math-block">
<div class="math-title">Disparate Impact (80% Rule β€” EEOC)</div>
DI = P(ΕΆ=1 | A=minority) / P(ΕΆ=1 | A=majority)<br>
DI &lt; 0.8 β†’ potential illegal discrimination<br><br>
<div class="math-title">Equalised Odds</div>
TPR(A=0) = TPR(A=1) AND FPR(A=0) = FPR(A=1)<br>
Equal true-positive AND false-positive rates across protected groups.<br><br>
<div class="math-title">Demographic Parity</div>
P(ΕΆ=1 | A=0) = P(ΕΆ=1 | A=1)<br>
Prediction rate is equal regardless of protected attribute.
</div>
<pre><code><span class="kw">from</span> fairlearn.metrics <span class="kw">import</span> MetricFrame, selection_rate, true_positive_rate
<span class="kw">from</span> fairlearn.reductions <span class="kw">import</span> ExponentiatedGradient, DemographicParity
<span class="kw">import</span> pandas <span class="kw">as</span> pd
<span class="cm"># Compute fairness metrics across protected groups</span>
mf = <span class="fn">MetricFrame</span>(
metrics={
<span class="str">"selection_rate"</span>: selection_rate,
<span class="str">"tpr"</span>: true_positive_rate,
},
y_true=y_test,
y_pred=y_pred,
sensitive_features=X_test[<span class="str">"gender"</span>] <span class="cm"># protected attribute</span>
)
<span class="fn">print</span>(mf.by_group)
<span class="fn">print</span>(<span class="str">"Disparate Impact:"</span>, mf.<span class="fn">difference</span>())
<span class="cm"># Bias mitigation with Exponentiated Gradient</span>
constraint = <span class="fn">DemographicParity</span>()
mitigator = <span class="fn">ExponentiatedGradient</span>(base_estimator, constraint)
mitigator.<span class="fn">fit</span>(X_train, y_train, sensitive_features=X_train[<span class="str">"gender"</span>])
y_pred_fair = mitigator.<span class="fn">predict</span>(X_test)
<div class="code-lang">python</div></code></pre>
<h3>PII Detection & Anonymisation</h3>
<pre><code><span class="kw">from</span> presidio_analyzer <span class="kw">import</span> AnalyzerEngine
<span class="kw">from</span> presidio_anonymizer <span class="kw">import</span> AnonymizerEngine
analyzer = <span class="fn">AnalyzerEngine</span>()
anonymizer = <span class="fn">AnonymizerEngine</span>()
text = <span class="str">"John Smith's email is john@example.com and his phone is +1-555-0123"</span>
results = analyzer.<span class="fn">analyze</span>(text=text, language=<span class="str">"en"</span>)
anonymized = anonymizer.<span class="fn">anonymize</span>(text=text, analyzer_results=results)
<span class="fn">print</span>(anonymized.text)
<span class="cm"># Output: "&lt;PERSON&gt;'s email is &lt;EMAIL_ADDRESS&gt; and phone is &lt;PHONE_NUMBER&gt;"</span>
<div class="code-lang">python</div></code></pre>
</div>
<!-- GOVERNANCE -->
<div class="section" id="sec-governance">
<div class="section-header">
<div class="section-num">08 β€” GOVERNANCE</div>
<h2>Data Governance <span class="accent3">&amp;</span> <span class="accent">Law</span></h2>
<p class="section-intro">Non-compliance with data sovereignty laws can result in fines up to 4% of global annual turnover (GDPR). As an ML engineer, you are legally responsible for the data your models ingest.</p>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>Regulation</th><th>Jurisdiction</th><th>Key Articles/Sections</th><th>ML-Specific Risk</th></tr></thead>
<tbody>
<tr>
<td><strong>GDPR</strong></td>
<td>EU / EEA</td>
<td>Art. 5 (principles), Art. 9 (sensitive data), Art. 17 (right to erasure), Art. 22 (automated decisions)</td>
<td>Profiling, automated credit/hiring decisions need human review. Right to explanation.</td>
</tr>
<tr>
<td><strong>CCPA / CPRA</strong></td>
<td>California, USA</td>
<td>Β§1798.100 (access), Β§1798.105 (deletion), Β§1798.120 (opt-out of sale)</td>
<td>Training data purchased from data brokers may be non-compliant.</td>
</tr>
<tr>
<td><strong>PDPB / DPDPA 2023</strong></td>
<td>India</td>
<td>Chapter II (processing), Chapter III (rights), Schedule I (consent)</td>
<td>Cross-border transfer restrictions. Localisation requirements for sensitive data.</td>
</tr>
<tr>
<td><strong>PIPL</strong></td>
<td>China</td>
<td>Art. 28 (sensitive personal info), Art. 38 (cross-border transfer), Art. 55 (AI assessment)</td>
<td>Mandatory impact assessment for automated decisions affecting individuals.</td>
</tr>
<tr>
<td><strong>EU AI Act (2024)</strong></td>
<td>EU</td>
<td>Art. 9 (risk management), Art. 10 (training data governance), Title III (high-risk AI)</td>
<td>High-risk systems (hiring, credit, health) require extensive data documentation and audits.</td>
</tr>
<tr>
<td><strong>HIPAA</strong></td>
<td>USA (healthcare)</td>
<td>45 CFR Β§164 (PHI handling), Safe Harbor de-identification</td>
<td>18 specific identifiers must be removed before ML training on health data.</td>
</tr>
<tr>
<td><strong>FERPA</strong></td>
<td>USA (education)</td>
<td>20 U.S.C. Β§1232g</td>
<td>Student records cannot be used for ML without explicit consent.</td>
</tr>
</tbody>
</table>
</div>
<h3>Data Governance Policy Framework</h3>
<div class="callout callout-warn">
<div class="callout-icon">⚠️</div>
<div class="callout-body">
<strong>EU AI Act β€” High-Risk Categories (Annex III)</strong>
<p>Systems used in biometric identification, critical infrastructure, education, employment, credit scoring, insurance, law enforcement, and border control are classified as HIGH-RISK and require conformity assessments, data governance documentation, and human oversight provisions before deployment.</p>
</div>
</div>
<h3>Data Classification Taxonomy</h3>
<div class="table-wrap">
<table>
<thead><tr><th>Level</th><th>Description</th><th>Examples</th><th>Controls Required</th></tr></thead>
<tbody>
<tr><td><span class="pill-red pill">Restricted</span></td><td>PII, PHI, financial credentials</td><td>SSN, medical records, passwords</td><td>Encryption at rest + transit, access logging, DLP</td></tr>
<tr><td><span class="pill-yellow pill">Confidential</span></td><td>Business-sensitive non-PII</td><td>Revenue data, ML model weights, IP</td><td>Role-based access, audit trails</td></tr>
<tr><td><span class="pill-purple pill">Internal</span></td><td>Operational data</td><td>Logs, metrics, employee data</td><td>Authentication, least-privilege</td></tr>
<tr><td><span class="pill">Public</span></td><td>Open data</td><td>Open-source datasets, press releases</td><td>Integrity checks only</td></tr>
</tbody>
</table>
</div>
</div>
<!-- DEPENDENCIES -->
<div class="section" id="sec-dependencies">
<div class="section-header">
<div class="section-num">09 β€” DEPENDENCIES</div>
<h2>Data <span class="accent2">Dependencies</span> & Security</h2>
<p class="section-intro">Your data pipeline's attack surface includes third-party data sources, library dependencies, and the trained model artifacts themselves. Data poisoning, model inversion attacks, and supply chain compromise are real production threats.</p>
</div>
<h3>Dependency Management</h3>
<pre><code><span class="cm"># pyproject.toml β€” pin dependencies with hash verification</span>
[tool.poetry.dependencies]
python = <span class="str">"^3.11"</span>
pandas = <span class="str">"~2.2"</span> <span class="cm"># minor version locked</span>
numpy = <span class="str">"~1.26"</span>
scikit-learn = <span class="str">"~1.4"</span>
torch = {version = <span class="str">"~2.2"</span>, extras = [<span class="str">"cuda12"</span>]}
<span class="cm"># Generate lock file with reproducible hashes</span>
<span class="cm"># poetry lock --no-update</span>
<span class="cm"># pip-compile --generate-hashes requirements.in</span>
<div class="code-lang">toml</div></code></pre>
<h3>Data Poisoning Defences</h3>
<div class="table-wrap">
<table>
<thead><tr><th>Attack Type</th><th>Description</th><th>Defence</th></tr></thead>
<tbody>
<tr><td><strong>Label Flipping</strong></td><td>Adversary corrupts labels in training set</td><td>Certified Data Cleaning, SEVER algorithm</td></tr>
<tr><td><strong>Backdoor/Trojan</strong></td><td>Trigger pattern inserted into training images</td><td>Neural Cleanse, Spectral Signatures detection</td></tr>
<tr><td><strong>Model Inversion</strong></td><td>Reconstruct training data from model outputs</td><td>Differential Privacy, output perturbation</td></tr>
<tr><td><strong>Membership Inference</strong></td><td>Determine if sample was in training set</td><td>DP-SGD training, prediction confidence limiting</td></tr>
<tr><td><strong>Supply Chain</strong></td><td>Malicious public dataset (e.g., poisoned LAION subset)</td><td>Hash-verify source, sandboxed ingestion</td></tr>
</tbody>
</table>
</div>
<h3>Differential Privacy for ML</h3>
<div class="math-block">
<div class="math-title">Ξ΅-Differential Privacy (DP)</div>
A mechanism M is Ξ΅-DP if for any adjacent datasets D, D' and any output S:<br>
P[M(D) ∈ S] ≀ e^Ξ΅ Γ— P[M(D') ∈ S]<br><br>
Ξ΅ = privacy budget: smaller = more private. Typical values: 0.1 (strong) to 10 (weak).<br><br>
<div class="math-title">Gaussian Mechanism (for DP-SGD)</div>
M(x) = f(x) + N(0, σ²ΔfΒ²) where Ξ”f = sensitivity of f, Οƒ = noise multiplier<br>
Clip gradients: gΜƒ = g / max(1, β€–gβ€–β‚‚/C) then add noise σ·CΒ·N(0,I)
</div>
<pre><code><span class="kw">from</span> opacus <span class="kw">import</span> PrivacyEngine
<span class="kw">import</span> torch
privacy_engine = <span class="fn">PrivacyEngine</span>()
model, optimizer, data_loader = privacy_engine.<span class="fn">make_private_with_epsilon</span>(
module=model,
optimizer=optimizer,
data_loader=data_loader,
epochs=<span class="num">50</span>,
target_epsilon=<span class="num">1.0</span>, <span class="cm"># strong privacy</span>
target_delta=<span class="num">1e-5</span>,
max_grad_norm=<span class="num">1.0</span>
)
<span class="fn">print</span>(<span class="str">f"Οƒ = {optimizer.noise_multiplier:.3f}"</span>)
<div class="code-lang">python</div></code></pre>
</div>
<!-- DISTRIBUTED PROCESSING -->
<div class="section" id="sec-distributed">
<div class="section-header">
<div class="section-num">10 β€” DISTRIBUTED</div>
<h2>Distributed <span class="accent">Processing</span></h2>
<p class="section-intro">When data doesn't fit in memory β€” or when processing must complete in minutes rather than hours β€” distributed computing is the answer. Memory management, garbage collection, and parallel I/O become first-class concerns.</p>
</div>
<h3>Memory Management Fundamentals</h3>
<div class="math-block">
<div class="math-title">Memory Estimation for a Dataset</div>
Memory (bytes) β‰ˆ rows Γ— cols Γ— bytes_per_dtype<br>
float64: 8 bytes/element | float32: 4 | int8: 1 | bool: 1<br>
Example: 100M rows Γ— 50 float32 cols = 100M Γ— 50 Γ— 4 = 20 GB<br><br>
<div class="math-title">Chunk Processing</div>
For a file of size F with available memory M_avail:<br>
chunk_size = floor(0.3 Γ— M_avail / bytes_per_row) rows<br>
Use 30% of available memory to leave room for transformations.
</div>
<pre><code><span class="kw">import</span> pandas <span class="kw">as</span> pd
<span class="kw">import</span> numpy <span class="kw">as</span> np
<span class="kw">from</span> concurrent.futures <span class="kw">import</span> ProcessPoolExecutor
<span class="kw">import</span> psutil, gc
<span class="kw">def</span> <span class="fn">process_chunk</span>(chunk: pd.DataFrame) -> pd.DataFrame:
<span class="str">"""Pure function β€” safe for multiprocessing"""</span>
chunk = chunk.<span class="fn">dropna</span>(subset=[<span class="str">"value"</span>])
chunk[<span class="str">"log_value"</span>] = np.<span class="fn">log1p</span>(chunk[<span class="str">"value"</span>])
<span class="kw">return</span> chunk
<span class="kw">def</span> <span class="fn">stream_process_csv</span>(filepath: str, chunksize: int = <span class="num">100_000</span>) -> pd.DataFrame:
<span class="str">"""
Memory-safe streaming CSV processing.
Processes in chunks, collects results, forces GC between chunks.
"""</span>
results = []
mem = psutil.<span class="fn">virtual_memory</span>()
safe_chunk = <span class="fn">int</span>((mem.available * <span class="num">0.3</span>) / (<span class="num">50</span> * <span class="num">8</span>)) <span class="cm"># estimate bytes per row</span>
<span class="kw">for</span> i, chunk <span class="kw">in</span> <span class="fn">enumerate</span>(pd.<span class="fn">read_csv</span>(filepath, chunksize=safe_chunk)):
processed = <span class="fn">process_chunk</span>(chunk)
results.<span class="fn">append</span>(processed)
<span class="kw">del</span> chunk, processed
gc.<span class="fn">collect</span>() <span class="cm"># explicit GC trigger</span>
<span class="kw">if</span> i % <span class="num">10</span> == <span class="num">0</span>:
<span class="fn">print</span>(<span class="str">f"Processed {i * safe_chunk:,} rows | "
f"Memory: {psutil.virtual_memory().percent:.1f}%"</span>)
<span class="kw">return</span> pd.<span class="fn">concat</span>(results, ignore_index=<span class="kw">True</span>)
<div class="code-lang">python</div></code></pre>
<h3>Apache Spark β€” DataFrame API Best Practices</h3>
<pre><code><span class="kw">from</span> pyspark.sql <span class="kw">import</span> SparkSession
<span class="kw">from</span> pyspark.sql <span class="kw">import</span> functions <span class="kw">as</span> F
<span class="kw">from</span> pyspark.sql.window <span class="kw">import</span> Window
<span class="kw">from</span> pyspark.ml.feature <span class="kw">import</span> StandardScaler, VectorAssembler
spark = (SparkSession.<span class="fn">builder</span>
.<span class="fn">appName</span>(<span class="str">"FeatureEngineering"</span>)
.<span class="fn">config</span>(<span class="str">"spark.sql.adaptive.enabled"</span>, <span class="str">"true"</span>) <span class="cm"># AQE for skew handling</span>
.<span class="fn">config</span>(<span class="str">"spark.sql.shuffle.partitions"</span>, <span class="str">"200"</span>)
.<span class="fn">config</span>(<span class="str">"spark.memory.offHeap.enabled"</span>, <span class="str">"true"</span>)
.<span class="fn">config</span>(<span class="str">"spark.memory.offHeap.size"</span>, <span class="str">"4g"</span>)
.<span class="fn">getOrCreate</span>())
df = spark.<span class="fn">read</span>.<span class="fn">parquet</span>(<span class="str">"s3://bucket/data/*.parquet"</span>)
<span class="cm"># Partition pruning β€” predicate pushed to storage layer</span>
df_filtered = df.<span class="fn">filter</span>((F.<span class="fn">col</span>(<span class="str">"year"</span>) == <span class="num">2024</span>) & (F.<span class="fn">col</span>(<span class="str">"region"</span>) == <span class="str">"APAC"</span>))
<span class="cm"># Window aggregation β€” distributed version of Pandas groupby</span>
w = Window.<span class="fn">partitionBy</span>(<span class="str">"user_id"</span>).<span class="fn">orderBy</span>(<span class="str">"ts"</span>).<span class="fn">rowsBetween</span>(-<span class="num">29</span>, <span class="num">0</span>)
df_feat = df_filtered.<span class="fn">withColumn</span>(
<span class="str">"rolling_30d"</span>, F.<span class="fn">sum</span>(<span class="str">"revenue"</span>).<span class="fn">over</span>(w)
)
<span class="cm"># Cache hot DataFrames β€” only if reused multiple times</span>
df_feat.<span class="fn">cache</span>().<span class="fn">count</span>() <span class="cm"># trigger materialisation</span>
<span class="cm"># Write back to Delta Lake (ACID)</span>
df_feat.<span class="fn">write</span>.<span class="fn">format</span>(<span class="str">"delta"</span>).<span class="fn">mode</span>(<span class="str">"overwrite"</span>).<span class="fn">save</span>(<span class="str">"s3://bucket/features/"</span>)
<div class="code-lang">python</div></code></pre>
<h3>Kafka β€” Streaming Data Pipeline</h3>
<pre><code><span class="kw">from</span> confluent_kafka <span class="kw">import</span> Consumer, Producer
<span class="kw">import</span> json
<span class="cm"># Producer: ingest raw events</span>
producer = <span class="fn">Producer</span>({<span class="str">"bootstrap.servers"</span>: <span class="str">"kafka:9092"</span>})
<span class="kw">def</span> <span class="fn">delivery_report</span>(err, msg):
<span class="kw">if</span> err:
<span class="fn">print</span>(<span class="str">f"Delivery failed: {err}"</span>)
<span class="kw">def</span> <span class="fn">publish_event</span>(topic: str, key: str, value: dict):
producer.<span class="fn">produce</span>(
topic, key=key.<span class="fn">encode</span>(),
value=json.<span class="fn">dumps</span>(value).<span class="fn">encode</span>(),
callback=delivery_report
)
producer.<span class="fn">poll</span>(<span class="num">0</span>) <span class="cm"># non-blocking flush</span>
<span class="cm"># Consumer: feature extraction from stream</span>
consumer = <span class="fn">Consumer</span>({
<span class="str">"bootstrap.servers"</span>: <span class="str">"kafka:9092"</span>,
<span class="str">"group.id"</span>: <span class="str">"feature-pipeline"</span>,
<span class="str">"auto.offset.reset"</span>: <span class="str">"earliest"</span>,
<span class="str">"enable.auto.commit"</span>: <span class="kw">False</span> <span class="cm"># manual commit = at-least-once</span>
})
consumer.<span class="fn">subscribe</span>([<span class="str">"raw-events"</span>])
<div class="code-lang">python</div></code></pre>
</div>
<!-- ERROR HANDLING -->
<div class="section" id="sec-errorhandling">
<div class="section-header">
<div class="section-num">11 β€” ERROR HANDLING</div>
<h2>Error Handling <span class="accent4">&amp;</span> Logging</h2>
<p class="section-intro">Production data pipelines fail silently and expensively. Robust error handling means the difference between a debugging session and an undetected data quality incident that corrupts a model in production.</p>
</div>
<h3>Structured Logging Pattern</h3>
<pre><code><span class="kw">import</span> structlog, logging, sys
<span class="kw">from</span> functools <span class="kw">import</span> wraps
<span class="cm"># Configure structured JSON logging</span>
structlog.<span class="fn">configure</span>(
processors=[
structlog.contextvars.<span class="fn">merge_contextvars</span>,
structlog.processors.<span class="fn">TimeStamper</span>(fmt=<span class="str">"iso"</span>),
structlog.processors.<span class="fn">add_log_level</span>,
structlog.processors.<span class="fn">StackInfoRenderer</span>(),
structlog.processors.<span class="fn">JSONRenderer</span>()
],
wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
logger_factory=structlog.<span class="fn">PrintLoggerFactory</span>()
)
logger = structlog.<span class="fn">get_logger</span>()
<span class="kw">def</span> <span class="fn">pipeline_step</span>(step_name: str):
<span class="str">"""Decorator: auto-log entry/exit/error for pipeline stages."""</span>
<span class="kw">def</span> decorator(func):
<span class="cls">@wraps</span>(func)
<span class="kw">def</span> wrapper(*args, **kwargs):
log = logger.<span class="fn">bind</span>(step=step_name, args_len=<span class="fn">len</span>(args))
log.<span class="fn">info</span>(<span class="str">"step.start"</span>)
<span class="kw">try</span>:
result = <span class="fn">func</span>(*args, **kwargs)
log.<span class="fn">info</span>(<span class="str">"step.success"</span>)
<span class="kw">return</span> result
<span class="kw">except</span> <span class="fn">ValueError</span> <span class="kw">as</span> e:
log.<span class="fn">error</span>(<span class="str">"step.validation_error"</span>, error=<span class="fn">str</span>(e), exc_info=<span class="kw">True</span>)
<span class="kw">raise</span>
<span class="kw">except</span> <span class="fn">Exception</span> <span class="kw">as</span> e:
log.<span class="fn">critical</span>(<span class="str">"step.fatal_error"</span>, error=<span class="fn">str</span>(e), exc_info=<span class="kw">True</span>)
<span class="kw">raise</span>
<span class="kw">return</span> wrapper
<span class="kw">return</span> decorator
<span class="cls">@pipeline_step</span>(<span class="str">"feature_normalisation"</span>)
<span class="kw">def</span> <span class="fn">normalise_features</span>(df):
<span class="kw">if</span> df.<span class="fn">empty</span>:
<span class="kw">raise</span> <span class="fn">ValueError</span>(<span class="str">"Input DataFrame is empty"</span>)
<span class="kw">return</span> (df - df.<span class="fn">mean</span>()) / df.<span class="fn">std</span>()
<div class="code-lang">python</div></code></pre>
<h3>Data Quality Monitoring with Evidently</h3>
<pre><code><span class="kw">from</span> evidently.report <span class="kw">import</span> Report
<span class="kw">from</span> evidently.metric_preset <span class="kw">import</span> DataDriftPreset, DataQualityPreset
report = <span class="fn">Report</span>(metrics=[
<span class="fn">DataDriftPreset</span>(),
<span class="fn">DataQualityPreset</span>()
])
report.<span class="fn">run</span>(reference_data=df_train, current_data=df_production)
report.<span class="fn">save_html</span>(<span class="str">"drift_report.html"</span>)
<span class="cm"># Raise alert if drift detected</span>
drift_result = report.as_dict()[<span class="str">"metrics"</span>][<span class="num">0</span>][<span class="str">"result"</span>]
<span class="kw">if</span> drift_result[<span class="str">"dataset_drift"</span>]:
<span class="kw">raise</span> <span class="fn">RuntimeError</span>(<span class="str">f"Data drift detected: {drift_result['share_of_drifted_columns']:.0%} columns drifted"</span>)
<div class="code-lang">python</div></code></pre>
</div>
<!-- TOOLS -->
<div class="section" id="sec-tools">
<div class="section-header">
<div class="section-num">12 β€” TOOLS</div>
<h2>Core Tools <span class="accent2">Deep Dive</span></h2>
<p class="section-intro">These five libraries form the computational backbone of modern ML data pipelines. Knowing not just their APIs but their performance characteristics and when to choose one over another is what separates seniors from juniors.</p>
</div>
<h3>NumPy β€” The Foundation</h3>
<div class="math-block">
<div class="math-title">Broadcasting Rules</div>
Two arrays are compatible if for each dimension pair:<br>
(a) they are equal, OR (b) one of them is 1<br>
Shape (3,1) + (1,4) β†’ broadcasts to (3,4)<br>
Shape (3,) + (4,3) β†’ error! Axes must align from the right.
</div>
<pre><code><span class="kw">import</span> numpy <span class="kw">as</span> np
<span class="cm"># Einstein summation β€” express any tensor contraction</span>
A = np.<span class="fn">random</span>.<span class="fn">randn</span>(<span class="num">100</span>, <span class="num">50</span>) <span class="cm"># batch_size Γ— features</span>
B = np.<span class="fn">random</span>.<span class="fn">randn</span>(<span class="num">50</span>, <span class="num">30</span>) <span class="cm"># features Γ— hidden</span>
C = np.<span class="fn">einsum</span>(<span class="str">"bi,ih->bh"</span>, A, B) <span class="cm"># equivalent to A @ B</span>
<span class="cm"># Vectorised cosine similarity matrix (no loops)</span>
<span class="kw">def</span> <span class="fn">cosine_similarity_matrix</span>(X: np.ndarray) -> np.ndarray:
norms = np.<span class="fn">linalg</span>.<span class="fn">norm</span>(X, axis=<span class="num">1</span>, keepdims=<span class="kw">True</span>) <span class="cm"># (n,1)</span>
X_norm = X / (norms + <span class="num">1e-8</span>) <span class="cm"># broadcast</span>
<span class="kw">return</span> X_norm @ X_norm.T <span class="cm"># (n,n)</span>
<span class="cm"># Memory-mapped arrays for out-of-core processing</span>
mmap = np.<span class="fn">memmap</span>(<span class="str">"large_array.npy"</span>, dtype=np.float32,
mode=<span class="str">"r"</span>, shape=(<span class="num">10_000_000</span>, <span class="num">128</span>))
batch = mmap[<span class="num">0</span>:<span class="num">1000</span>].<span class="fn">copy</span>() <span class="cm"># loads only this slice into RAM</span>
<div class="code-lang">python</div></code></pre>
<h3>Pandas β€” Advanced Patterns</h3>
<pre><code><span class="kw">import</span> pandas <span class="kw">as</span> pd
<span class="cm"># Method chaining β€” readable, pipe-based transformations</span>
result = (
pd.<span class="fn">read_parquet</span>(<span class="str">"events.parquet"</span>)
.<span class="fn">pipe</span>(<span class="fn">reduce_memory</span>)
.<span class="fn">query</span>(<span class="str">"event_type == 'purchase' and amount > 0"</span>)
.<span class="fn">assign</span>(
log_amount = <span class="kw">lambda</span> df: np.<span class="fn">log1p</span>(df[<span class="str">"amount"</span>]),
hour_of_day = <span class="kw">lambda</span> df: df[<span class="str">"timestamp"</span>].dt.hour
)
.<span class="fn">groupby</span>([<span class="str">"user_id"</span>, pd.<span class="fn">Grouper</span>(key=<span class="str">"timestamp"</span>, freq=<span class="str">"1D"</span>)])
.<span class="fn">agg</span>(daily_revenue=(<span class="str">"amount"</span>, <span class="str">"sum"</span>), n_purchases=(<span class="str">"amount"</span>, <span class="str">"count"</span>))
.<span class="fn">reset_index</span>()
)
<div class="code-lang">python</div></code></pre>
<h3>JAX β€” For High-Performance ML Research</h3>
<div class="math-block">
<div class="math-title">JAX Transforms (Composable Functional Transformations)</div>
jit(f) β†’ XLA-compiled version of f<br>
grad(f) β†’ gradient function βˆ‚f/βˆ‚x<br>
vmap(f) β†’ vectorised map (batching over a new axis)<br>
pmap(f) β†’ parallel map across devices (GPUs/TPUs)<br>
These compose: grad(jit(f)), vmap(grad(f)), etc.
</div>
<pre><code><span class="kw">import</span> jax.numpy <span class="kw">as</span> jnp
<span class="kw">from</span> jax <span class="kw">import</span> grad, jit, vmap, random
<span class="cm"># Automatic differentiation through any computation</span>
<span class="kw">def</span> <span class="fn">mse_loss</span>(params, X, y):
predictions = jnp.<span class="fn">dot</span>(X, params[<span class="str">"w"</span>]) + params[<span class="str">"b"</span>]
<span class="kw">return</span> jnp.<span class="fn">mean</span>((predictions - y) ** <span class="num">2</span>)
grad_fn = jit(<span class="fn">grad</span>(mse_loss)) <span class="cm"># compiled gradient function</span>
grads = <span class="fn">grad_fn</span>(params, X_batch, y_batch) <span class="cm"># {w: dL/dw, b: dL/db}</span>
<span class="cm"># vmap: apply single-sample function to a batch (no for-loop!)</span>
<span class="kw">def</span> <span class="fn">predict_single</span>(params, x):
<span class="kw">return</span> jnp.<span class="fn">dot</span>(x, params)
predict_batch = <span class="fn">vmap</span>(predict_single, in_axes=(<span class="kw">None</span>, <span class="num">0</span>)) <span class="cm"># params fixed, x batched</span>
<div class="code-lang">python</div></code></pre>
<h3>PyTorch β€” Production Data Loading</h3>
<pre><code><span class="kw">import</span> torch
<span class="kw">from</span> torch.utils.data <span class="kw">import</span> Dataset, DataLoader
<span class="kw">from</span> torch.utils.data.distributed <span class="kw">import</span> DistributedSampler
<span class="kw">class</span> <span class="cls">TabularDataset</span>(Dataset):
<span class="kw">def</span> <span class="fn">__init__</span>(self, X: np.ndarray, y: np.ndarray):
self.X = torch.<span class="fn">tensor</span>(X, dtype=torch.float32)
self.y = torch.<span class="fn">tensor</span>(y, dtype=torch.long)
<span class="kw">def</span> <span class="fn">__len__</span>(self): <span class="kw">return</span> <span class="fn">len</span>(self.X)
<span class="kw">def</span> <span class="fn">__getitem__</span>(self, idx): <span class="kw">return</span> self.X[idx], self.y[idx]
<span class="cm"># Production DataLoader with pinned memory for GPU transfer</span>
loader = <span class="fn">DataLoader</span>(
<span class="fn">TabularDataset</span>(X_train, y_train),
batch_size=<span class="num">512</span>,
num_workers=<span class="num">4</span>, <span class="cm"># parallel data loading workers</span>
pin_memory=<span class="kw">True</span>, <span class="cm"># faster CPU→GPU transfer</span>
persistent_workers=<span class="kw">True</span>, <span class="cm"># avoid re-spawning workers each epoch</span>
prefetch_factor=<span class="num">2</span>, <span class="cm"># pre-fetch 2 batches ahead</span>
sampler=<span class="fn">DistributedSampler</span>(dataset) <span class="cm"># for multi-GPU DDP</span>
)
<div class="code-lang">python</div></code></pre>
<h3>TensorFlow / Keras β€” Production Data Pipelines</h3>
<p>TensorFlow's <code>tf.data</code> API is the gold standard for building GPU-saturating input pipelines. The key is to overlap data loading (I/O-bound) with model execution (compute-bound) using <strong>prefetching</strong> and <strong>parallel map</strong>.</p>
<div class="math-block">
<div class="math-title">tf.data Performance Model</div>
Pipeline throughput = min(data_throughput, compute_throughput)<br>
With prefetch(AUTOTUNE): data_throughput overlaps with compute_throughput<br>
Without prefetch: total_time = Ξ£(data_time_i + compute_time_i) [sequential]<br>
With prefetch: total_time β‰ˆ max(Ξ£ data_time_i, Ξ£ compute_time_i) [pipelined]
</div>
<pre><code><span class="kw">import</span> tensorflow <span class="kw">as</span> tf
<span class="kw">import</span> numpy <span class="kw">as</span> np
<span class="cm"># Production tf.data pipeline β€” saturate GPU with parallel I/O</span>
<span class="kw">def</span> <span class="fn">build_training_pipeline</span>(
file_pattern: str,
batch_size: int = <span class="num">512</span>,
num_parallel_reads: int = <span class="num">8</span>,
shuffle_buffer: int = <span class="num">10_000</span>
) -> tf.data.Dataset:
<span class="str">"""High-performance TFRecord pipeline with:
- Parallel file interleaving
- Prefetch with AUTOTUNE
- Cached in-memory after first epoch
"""</span>
feature_spec = {
<span class="str">"features"</span>: tf.io.<span class="fn">FixedLenFeature</span>([<span class="num">128</span>], tf.float32),
<span class="str">"label"</span>: tf.io.<span class="fn">FixedLenFeature</span>([], tf.int64),
}
<span class="kw">def</span> <span class="fn">parse_example</span>(serialized):
parsed = tf.io.<span class="fn">parse_single_example</span>(serialized, feature_spec)
<span class="kw">return</span> parsed[<span class="str">"features"</span>], parsed[<span class="str">"label"</span>]
files = tf.data.Dataset.<span class="fn">list_files</span>(file_pattern, shuffle=<span class="kw">True</span>)
ds = files.<span class="fn">interleave</span>(
<span class="kw">lambda</span> f: tf.data.<span class="fn">TFRecordDataset</span>(f, compression_type=<span class="str">"GZIP"</span>),
num_parallel_calls=tf.data.AUTOTUNE,
cycle_length=num_parallel_reads,
deterministic=<span class="kw">False</span> <span class="cm"># non-deterministic for speed</span>
)
ds = (
ds
.<span class="fn">shuffle</span>(shuffle_buffer)
.<span class="fn">map</span>(parse_example, num_parallel_calls=tf.data.AUTOTUNE)
.<span class="fn">batch</span>(batch_size, drop_remainder=<span class="kw">True</span>) <span class="cm"># drop_remainder for TPU</span>
.<span class="fn">cache</span>() <span class="cm"># cache after first epoch (fits in RAM)</span>
.<span class="fn">prefetch</span>(tf.data.AUTOTUNE) <span class="cm"># overlap data prep with training</span>
)
<span class="kw">return</span> ds
<span class="cm"># Keras model with mixed precision (2Γ— speed on modern GPUs)</span>
tf.keras.mixed_precision.<span class="fn">set_global_policy</span>(<span class="str">"mixed_float16"</span>)
model = tf.keras.<span class="fn">Sequential</span>([
tf.keras.layers.<span class="fn">Dense</span>(<span class="num">256</span>, activation=<span class="str">"relu"</span>, input_shape=(<span class="num">128</span>,)),
tf.keras.layers.<span class="fn">BatchNormalization</span>(),
tf.keras.layers.<span class="fn">Dropout</span>(<span class="num">0.3</span>),
tf.keras.layers.<span class="fn">Dense</span>(<span class="num">64</span>, activation=<span class="str">"relu"</span>),
tf.keras.layers.<span class="fn">Dense</span>(<span class="num">1</span>, activation=<span class="str">"sigmoid"</span>, dtype=<span class="str">"float32"</span>)
])
<span class="cm"># Compile with TF's built-in AUC metric for imbalanced data</span>
model.<span class="fn">compile</span>(
optimizer=tf.keras.optimizers.<span class="fn">Adam</span>(learning_rate=<span class="num">1e-3</span>),
loss=<span class="str">"binary_crossentropy"</span>,
metrics=[tf.keras.metrics.<span class="fn">AUC</span>(name=<span class="str">"auroc"</span>)]
)
train_ds = <span class="fn">build_training_pipeline</span>(<span class="str">"gs://bucket/train/*.tfrecord"</span>)
model.<span class="fn">fit</span>(train_ds, epochs=<span class="num">50</span>, callbacks=[
tf.keras.callbacks.<span class="fn">EarlyStopping</span>(monitor=<span class="str">"val_auroc"</span>, patience=<span class="num">5</span>, mode=<span class="str">"max"</span>),
tf.keras.callbacks.<span class="fn">ModelCheckpoint</span>(<span class="str">"best_model.keras"</span>, save_best_only=<span class="kw">True</span>)
])
<span class="cm"># Export to SavedModel for TF Serving / TFLite</span>
model.<span class="fn">export</span>(<span class="str">"saved_model/fraud_detector"</span>)
<div class="code-lang">python</div></code></pre>
<div class="callout callout-info">
<div class="callout-icon">πŸ”§</div>
<div class="callout-body">
<strong>TensorFlow vs PyTorch β€” When to Choose TF</strong>
<p>Choose TensorFlow when: (1) deploying via TF Serving, TFLite, or TF.js, (2) training on Google TPUs (native TPU Strategy), (3) using Vertex AI or GCP ML stack, (4) your team has existing TF infrastructure. PyTorch has won the research ecosystem, but TF remains dominant in production serving at scale β€” especially at Google, DeepMind, and companies using GCP.</p>
</div>
</div>
<h3>When to Use Which Tool</h3>
<div class="table-wrap">
<table>
<thead><tr><th>Scenario</th><th>Best Tool</th><th>Why</th></tr></thead>
<tbody>
<tr><td>Statistical analysis, EDA</td><td>Pandas + NumPy</td><td>Rich API, Jupyter integration</td></tr>
<tr><td>ML research, custom gradients</td><td>JAX + Flax/Optax</td><td>Composable transforms, XLA JIT</td></tr>
<tr><td>Deep learning production</td><td>PyTorch + TorchScript</td><td>Ecosystem, ONNX export, deployment</td></tr>
<tr><td>TF Serving / TPU training</td><td>TensorFlow / Keras</td><td>Best for Google Cloud, TPU support</td></tr>
<tr><td>Large matrix ops, PCA, SVD</td><td>NumPy / JAX</td><td>Broadcasting, einsum, linalg</td></tr>
<tr><td>Petabyte-scale feature eng.</td><td>PySpark + Delta Lake</td><td>Distributed, ACID, versioned</td></tr>
</tbody>
</table>
</div>
</div>
<!-- SCRAPING -->
<div class="section" id="sec-scraping">
<div class="section-header">
<div class="section-num">13 β€” WEB SCRAPING</div>
<h2>Web <span class="accent">Scraping</span></h2>
<p class="section-intro">Web scraping is a last resort for data collection β€” always prefer APIs and open datasets. When scraping is necessary, these tools handle modern JavaScript-heavy sites, bot detection, and scale.</p>
</div>
<div class="callout callout-danger">
<div class="callout-icon">βš–οΈ</div>
<div class="callout-body">
<strong>Legal Prerequisites Before Scraping</strong>
<p>Check robots.txt. Review the site's Terms of Service. Scraping content protected by copyright without licence is legally risky (see hiQ v. LinkedIn; Meta v. Bright Data). Never scrape PII without explicit legal basis. Rate-limit your requests to avoid DoS liability.</p>
</div>
</div>
<h3>Crawlee (Node.js) β€” Enterprise Scraping</h3>
<pre><code><span class="cm">// Crawlee with Playwright for JS-heavy sites</span>
<span class="kw">import</span> { PlaywrightCrawler, Dataset } from <span class="str">'crawlee'</span>;
<span class="kw">const</span> crawler = <span class="kw">new</span> <span class="fn">PlaywrightCrawler</span>({
maxRequestsPerCrawl: <span class="num">1000</span>,
maxConcurrency: <span class="num">5</span>,
requestHandlerTimeoutSecs: <span class="num">30</span>,
async requestHandler({ page, request, enqueueLinks }) {
<span class="cm">// Wait for dynamic content</span>
await page.<span class="fn">waitForSelector</span>(<span class="str">'.product-card'</span>, { timeout: <span class="num">10000</span> });
<span class="kw">const</span> items = await page.<span class="fn">$$eval</span>(<span class="str">'.product-card'</span>, cards =>
cards.<span class="fn">map</span>(c => ({
title: c.<span class="fn">querySelector</span>(<span class="str">'h2'</span>)?.textContent,
price: c.<span class="fn">querySelector</span>(<span class="str">'.price'</span>)?.textContent,
url: c.<span class="fn">querySelector</span>(<span class="str">'a'</span>)?.href
}))
);
await Dataset.<span class="fn">pushData</span>(items);
await <span class="fn">enqueueLinks</span>({ selector: <span class="str">'a.next-page'</span> });
},
failedRequestHandler: ({ request }) =>
console.error(<span class="str">`Failed: ${request.url}`</span>)
});
await crawler.<span class="fn">run</span>([<span class="str">'https://example.com/products'</span>]);
<div class="code-lang">javascript</div></code></pre>
<h3>Crawl4AI β€” LLM-Powered Extraction (Python)</h3>
<pre><code><span class="kw">from</span> crawl4ai <span class="kw">import</span> AsyncWebCrawler
<span class="kw">from</span> crawl4ai.extraction_strategy <span class="kw">import</span> LLMExtractionStrategy
<span class="kw">import</span> asyncio, json
<span class="kw">async def</span> <span class="fn">extract_structured_data</span>(url: str):
strategy = <span class="fn">LLMExtractionStrategy</span>(
provider=<span class="str">"openai/gpt-4o-mini"</span>,
api_token=<span class="str">"YOUR_KEY"</span>,
schema={
<span class="str">"type"</span>: <span class="str">"object"</span>,
<span class="str">"properties"</span>: {
<span class="str">"company_name"</span>: {<span class="str">"type"</span>: <span class="str">"string"</span>},
<span class="str">"founding_year"</span>: {<span class="str">"type"</span>: <span class="str">"integer"</span>},
<span class="str">"revenue"</span>: {<span class="str">"type"</span>: <span class="str">"number"</span>}
}
},
instruction=<span class="str">"Extract company details from the page."</span>
)
<span class="kw">async with</span> <span class="fn">AsyncWebCrawler</span>(verbose=<span class="kw">True</span>) <span class="kw">as</span> crawler:
result = <span class="kw">await</span> crawler.<span class="fn">arun</span>(url=url, extraction_strategy=strategy)
<span class="kw">return</span> json.<span class="fn">loads</span>(result.extracted_content)
asyncio.<span class="fn">run</span>(<span class="fn">extract_structured_data</span>(<span class="str">"https://example.com/about"</span>))
<div class="code-lang">python</div></code></pre>
<h3>Puppeteer β€” Headless Browser Scraping (Node.js)</h3>
<pre><code><span class="cm">// Puppeteer with stealth plugin β€” handles SPAs and bot detection</span>
<span class="kw">import</span> puppeteer from <span class="str">'puppeteer-extra'</span>;
<span class="kw">import</span> StealthPlugin from <span class="str">'puppeteer-extra-plugin-stealth'</span>;
<span class="kw">import</span> fs from <span class="str">'fs/promises'</span>;
puppeteer.<span class="fn">use</span>(<span class="fn">StealthPlugin</span>());
<span class="kw">async function</span> <span class="fn">scrapeProducts</span>(url) {
<span class="kw">const</span> browser = <span class="kw">await</span> puppeteer.<span class="fn">launch</span>({
headless: <span class="str">'new'</span>, <span class="cm">// new headless mode (Chrome 112+)</span>
args: [
<span class="str">'--no-sandbox'</span>,
<span class="str">'--disable-setuid-sandbox'</span>,
<span class="str">'--disable-dev-shm-usage'</span> <span class="cm">// for Docker</span>
]
});
<span class="kw">const</span> page = <span class="kw">await</span> browser.<span class="fn">newPage</span>();
<span class="kw">await</span> page.<span class="fn">setViewport</span>({ width: <span class="num">1280</span>, height: <span class="num">800</span> });
<span class="cm">// Navigate and wait for dynamic content</span>
<span class="kw">await</span> page.<span class="fn">goto</span>(url, { waitUntil: <span class="str">'networkidle0'</span>, timeout: <span class="num">30000</span> });
<span class="cm">// Auto-scroll to trigger lazy-loaded content</span>
<span class="kw">await</span> page.<span class="fn">evaluate</span>(<span class="kw">async</span> () => {
<span class="kw">await new</span> Promise(resolve => {
<span class="kw">let</span> totalHeight = <span class="num">0</span>;
<span class="kw">const</span> distance = <span class="num">300</span>;
<span class="kw">const</span> timer = <span class="fn">setInterval</span>(() => {
window.<span class="fn">scrollBy</span>(<span class="num">0</span>, distance);
totalHeight += distance;
<span class="kw">if</span> (totalHeight >= document.body.scrollHeight) {
<span class="fn">clearInterval</span>(timer);
<span class="fn">resolve</span>();
}
}, <span class="num">200</span>);
});
});
<span class="cm">// Extract structured data</span>
<span class="kw">const</span> products = <span class="kw">await</span> page.<span class="fn">$$eval</span>(<span class="str">'.product-item'</span>, items =>
items.<span class="fn">map</span>(el => ({
name: el.<span class="fn">querySelector</span>(<span class="str">'h3'</span>)?.textContent?.<span class="fn">trim</span>(),
price: <span class="fn">parseFloat</span>(el.<span class="fn">querySelector</span>(<span class="str">'.price'</span>)?.textContent?.<span class="fn">replace</span>(<span class="str">/[^0-9.]/g</span>, <span class="str">''</span>)),
rating: <span class="fn">parseFloat</span>(el.<span class="fn">querySelector</span>(<span class="str">'[data-rating]'</span>)?.<span class="fn">getAttribute</span>(<span class="str">'data-rating'</span>)),
url: el.<span class="fn">querySelector</span>(<span class="str">'a'</span>)?.href
}))
);
<span class="kw">await</span> fs.<span class="fn">writeFile</span>(<span class="str">'products.json'</span>, JSON.<span class="fn">stringify</span>(products, <span class="kw">null</span>, <span class="num">2</span>));
console.<span class="fn">log</span>(<span class="str">`Scraped ${products.length} products`</span>);
<span class="kw">await</span> browser.<span class="fn">close</span>();
<span class="kw">return</span> products;
}
<span class="fn">scrapeProducts</span>(<span class="str">'https://example.com/shop'</span>);
<div class="code-lang">javascript</div></code></pre>
<div class="callout callout-info">
<div class="callout-icon">πŸ†š</div>
<div class="callout-body">
<strong>Puppeteer vs Playwright vs Crawlee</strong>
<p><strong>Puppeteer</strong>: Chrome/Chromium only, lightweight, excellent for single-browser tasks and Google ecosystem. <strong>Playwright</strong>: Multi-browser (Chrome, Firefox, WebKit), auto-wait, better for cross-browser testing and complex flows. <strong>Crawlee</strong>: Built on Playwright/Puppeteer, adds queue management, auto-scaling, proxy rotation β€” best for large-scale production crawling. Choose Puppeteer for simplicity, Playwright for robustness, Crawlee for scale.</p>
</div>
</div>
<h3>Playwright β€” Anti-Bot Techniques</h3>
<pre><code><span class="kw">from</span> playwright.async_api <span class="kw">import</span> async_playwright
<span class="kw">import</span> asyncio, random
<span class="kw">async def</span> <span class="fn">stealth_scrape</span>(url: str):
<span class="kw">async with</span> <span class="fn">async_playwright</span>() <span class="kw">as</span> p:
browser = <span class="kw">await</span> p.chromium.<span class="fn">launch</span>(
headless=<span class="kw">True</span>,
args=[<span class="str">'--disable-blink-features=AutomationControlled'</span>]
)
context = <span class="kw">await</span> browser.<span class="fn">new_context</span>(
user_agent=<span class="str">"Mozilla/5.0 (Windows NT 10.0; Win64; x64)..."</span>,
viewport={<span class="str">"width"</span>: <span class="num">1280</span>, <span class="str">"height"</span>: <span class="num">800</span>},
locale=<span class="str">"en-US"</span>
)
<span class="cm"># Mask navigator.webdriver fingerprint</span>
<span class="kw">await</span> context.<span class="fn">add_init_script</span>(
<span class="str">"Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"</span>
)
page = <span class="kw">await</span> context.<span class="fn">new_page</span>()
<span class="kw">await</span> page.<span class="fn">goto</span>(url, wait_until=<span class="str">"networkidle"</span>)
<span class="cm"># Human-like delay</span>
<span class="kw">await</span> asyncio.<span class="fn">sleep</span>(random.<span class="fn">uniform</span>(<span class="num">1.5</span>, <span class="num">3.5</span>))
content = <span class="kw">await</span> page.<span class="fn">content</span>()
<span class="kw">await</span> browser.<span class="fn">close</span>()
<span class="kw">return</span> content
<div class="code-lang">python</div></code></pre>
</div>
<!-- SYNTHETIC DATA -->
<div class="section" id="sec-synthetic">
<div class="section-header">
<div class="section-num">14 β€” SYNTHETIC DATA</div>
<h2>Synthetic Data <span class="accent2">&amp;</span> <span class="accent">GenAI</span></h2>
<p class="section-intro">Synthetic data generation bridges the gap between limited labelled data and model training requirements. When used correctly it preserves statistical properties while removing privacy risks.</p>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>Tool</th><th>Type</th><th>Best For</th><th>Licence</th></tr></thead>
<tbody>
<tr><td><strong>SDV (Synthetic Data Vault)</strong></td><td>Statistical / DL</td><td>Tabular, relational, time-series</td><td><span class="pill">BSL (free tiers)</span></td></tr>
<tr><td><strong>CTGAN / TVAE</strong></td><td>GAN / VAE</td><td>Tabular with mixed types</td><td><span class="pill">MIT</span></td></tr>
<tr><td><strong>Gretel.ai</strong></td><td>DGAN, Actgan</td><td>Privacy-safe enterprise data</td><td><span class="pill-purple pill">SaaS</span></td></tr>
<tr><td><strong>Faker</strong></td><td>Rule-based</td><td>PII generation, testing</td><td><span class="pill">MIT</span></td></tr>
<tr><td><strong>DiffPrivLib</strong></td><td>DP mechanisms</td><td>Privacy-preserving statistics</td><td><span class="pill">MIT</span></td></tr>
<tr><td><strong>Mimesis</strong></td><td>Rule-based</td><td>Multi-locale fake data</td><td><span class="pill">MIT</span></td></tr>
<tr><td><strong>Augly (Meta)</strong></td><td>Augmentation</td><td>Text, image, video augmentation</td><td><span class="pill">MIT</span></td></tr>
<tr><td><strong>Albumentations</strong></td><td>Image augmentation</td><td>CV training data expansion</td><td><span class="pill">MIT</span></td></tr>
<tr><td><strong>Claude / GPT-4o API</strong></td><td>LLM generation</td><td>NLP datasets, instruction tuning</td><td><span class="pill-yellow pill">API</span></td></tr>
</tbody>
</table>
</div>
<div class="math-block">
<div class="math-title">CTGAN β€” Conditional GAN for Tabular Data</div>
Generator G(z, c) β†’ synthetic row | Discriminator D(x, c) β†’ real/fake<br>
Objective: min_G max_D E[log D(x,c)] + E[log(1 βˆ’ D(G(z,c), c))]<br>
Mode-specific normalisation: each numeric column modelled as mixture of Gaussians<br>
Conditional vector c handles class imbalance by sampling under-represented classes.
</div>
<pre><code><span class="kw">from</span> sdv.single_table <span class="kw">import</span> CTGANSynthesizer
<span class="kw">from</span> sdv.metadata <span class="kw">import</span> SingleTableMetadata
<span class="kw">from</span> sdv.evaluation.single_table <span class="kw">import</span> run_diagnostic, evaluate_quality
metadata = <span class="fn">SingleTableMetadata</span>()
metadata.<span class="fn">detect_from_dataframe</span>(df_real)
metadata.<span class="fn">update_column</span>(<span class="str">"user_id"</span>, sdtype=<span class="str">"id"</span>) <span class="cm"># mark as ID, not feature</span>
metadata.<span class="fn">update_column</span>(<span class="str">"churn"</span>, sdtype=<span class="str">"categorical"</span>) <span class="cm"># target column</span>
synthesizer = <span class="fn">CTGANSynthesizer</span>(
metadata,
epochs=<span class="num">300</span>,
batch_size=<span class="num">500</span>,
discriminator_steps=<span class="num">1</span>,
verbose=<span class="kw">True</span>
)
synthesizer.<span class="fn">fit</span>(df_real)
df_synthetic = synthesizer.<span class="fn">sample</span>(num_rows=<span class="num">50_000</span>)
<span class="cm"># Evaluate quality: column shapes + correlation</span>
quality = <span class="fn">evaluate_quality</span>(df_real, df_synthetic, metadata)
<span class="fn">print</span>(<span class="str">f"Quality Score: {quality.get_score():.2f}"</span>) <span class="cm"># aim for &gt;0.85</span>
<div class="code-lang">python</div></code></pre>
<h3>LLM-Powered Synthetic NLP Dataset Pipeline</h3>
<pre><code><span class="kw">import</span> anthropic, json
<span class="kw">from</span> typing <span class="kw">import</span> Iterator
client = anthropic.<span class="fn">Anthropic</span>()
<span class="kw">def</span> <span class="fn">generate_synthetic_samples</span>(
task: str, labels: list, n_per_label: int = <span class="num">100</span>
) -> Iterator[dict]:
<span class="str">"""Generate labelled NLP training samples via Claude."""</span>
<span class="kw">for</span> label <span class="kw">in</span> labels:
prompt = <span class="str">f"""Generate {n_per_label} diverse text samples for a {task} classifier.
Label: {label}
Requirements:
- Vary writing style (formal, casual, terse, verbose)
- Vary sentiment polarity where applicable
- Avoid exact duplicates
Return ONLY a JSON array of strings, no extra text."""</span>
msg = client.messages.<span class="fn">create</span>(
model=<span class="str">"claude-sonnet-4-6"</span>,
max_tokens=<span class="num">4096</span>,
messages=[{<span class="str">"role"</span>: <span class="str">"user"</span>, <span class="str">"content"</span>: prompt}]
)
samples = json.<span class="fn">loads</span>(msg.content[<span class="num">0</span>].text)
<span class="kw">for</span> text <span class="kw">in</span> samples:
<span class="kw">yield</span> {<span class="str">"text"</span>: text, <span class="str">"label"</span>: label}
<div class="code-lang">python</div></code></pre>
</div>
<!-- DATABASES -->
<div class="section" id="sec-databases">
<div class="section-header">
<div class="section-num">15 β€” DATABASES</div>
<h2>Database Selection <span class="accent">2026</span></h2>
<p class="section-intro">You listed 7 databases. The truth is: a senior ML engineer in 2026 needs at most 3 database types in their core stack. Here's the full landscape, and then the verdict.</p>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>Database</th><th>Type</th><th>ML Use Case</th><th>Strengths</th><th>Avoid When</th></tr></thead>
<tbody>
<tr><td><strong>PostgreSQL</strong></td><td>OLTP / Relational</td><td>Feature metadata, experiment tracking, label storage</td><td>ACID, extensions (pgvector!), mature ecosystem</td><td>Analytical queries on billions of rows</td></tr>
<tr><td><strong>DuckDB</strong></td><td>Embedded OLAP</td><td>Local EDA, feature engineering, parquet/CSV analytics</td><td>Blazing fast columnar, runs in Python process, no server</td><td>Multi-user concurrent writes</td></tr>
<tr><td><strong>CockroachDB</strong></td><td>NewSQL / Distributed</td><td>Global feature stores needing strong consistency</td><td>Distributed ACID, Postgres-compatible, geo-partitioning</td><td>Pure analytics β€” too expensive for OLAP</td></tr>
<tr><td><strong>MongoDB</strong></td><td>Document / NoSQL</td><td>Semi-structured data ingestion, raw event storage</td><td>Flexible schema, Atlas Vector Search</td><td>Tabular ML features β€” use a proper warehouse</td></tr>
<tr><td><strong>ChromaDB</strong></td><td>Vector DB (local)</td><td>Embedding search, RAG prototyping, semantic dedup</td><td>Zero-ops, in-process, great for prototypes</td><td>Production at scale (&gt;10M vectors)</td></tr>
<tr><td><strong>Pinecone</strong></td><td>Vector DB (managed)</td><td>Production RAG, semantic search, recommendation</td><td>Managed, fast approximate NN, filtering</td><td>Cost-sensitive startups, offline/air-gap</td></tr>
<tr><td><strong>Neo4j</strong></td><td>Graph DB</td><td>Fraud detection, knowledge graphs, GNNs</td><td>Cypher query language, GraphSAGE integration, APOC</td><td>Tabular data β€” significant overhead</td></tr>
</tbody>
</table>
</div>
<h3>The Verdict β€” ML Engineer Stack 2026</h3>
<div class="db-winner">
<div class="db-name">πŸ₯‡ DuckDB</div>
<div class="db-subtitle">Primary: Local Analytics & EDA (replace Pandas for files &gt;1GB)</div>
<p style="margin-top:0.75rem; color:#c9ccd6; font-size:0.9rem;">DuckDB is the single most impactful addition to an ML workflow in 2024–2026. It runs inside your Python process, reads Parquet/CSV/Arrow directly, executes vectorised SQL at near-Spark speed on a laptop, integrates natively with Pandas and PyArrow, and has zero infrastructure overhead. For everything that fits on one machine, DuckDB should be your first choice.</p>
</div>
<div class="db-winner" style="background:linear-gradient(135deg,rgba(124,109,255,0.08),rgba(124,109,255,0.02));border-color:rgba(124,109,255,0.3)">
<div class="db-name" style="color:var(--accent2)">πŸ₯ˆ PostgreSQL + pgvector</div>
<div class="db-subtitle">Operational: Structured data + vector search in one system</div>
<p style="margin-top:0.75rem; color:#c9ccd6; font-size:0.9rem;">PostgreSQL with the pgvector extension handles both traditional relational data (experiment runs, model metadata, user features) AND vector similarity search. This eliminates a separate vector DB for most use cases under 1M vectors. Use with Supabase for zero-ops deployment.</p>
</div>
<div class="db-winner" style="background:linear-gradient(135deg,rgba(255,107,107,0.08),rgba(255,107,107,0.02));border-color:rgba(255,107,107,0.3)">
<div class="db-name" style="color:var(--accent3)">πŸ₯‰ Neo4j (Conditional)</div>
<div class="db-subtitle">Specialist: Only if your problem is fundamentally graph-shaped</div>
<p style="margin-top:0.75rem; color:#c9ccd6; font-size:0.9rem;">If your ML problem involves fraud detection, knowledge graphs, recommendation via graph traversal, or GNNs β€” Neo4j is irreplaceable. Otherwise, skip it. MongoDB and CockroachDB are appropriate in specific scenarios (unstructured ingestion and distributed OLTP respectively) but are not core ML tools.</p>
</div>
<pre><code><span class="kw">import</span> duckdb
<span class="kw">import</span> pandas <span class="kw">as</span> pd
<span class="cm"># DuckDB β€” the ML engineer's Swiss army knife</span>
con = duckdb.<span class="fn">connect</span>(<span class="str">"ml_features.duckdb"</span>)
<span class="cm"># Read Parquet directly β€” no loading into memory first!</span>
result = con.<span class="fn">execute</span>(<span class="str">"""
SELECT
user_id,
AVG(amount) FILTER (WHERE event_type='purchase') AS avg_purchase,
COUNT(*) FILTER (WHERE event_type='click') AS click_count,
APPROX_QUANTILE(amount, 0.95) AS p95_amount
FROM read_parquet('s3://bucket/events/*.parquet')
WHERE YEAR(event_date) = 2024
GROUP BY user_id
HAVING COUNT(*) > 10
"""</span>).<span class="fn">df</span>()
<span class="cm"># Write feature table back to parquet</span>
con.<span class="fn">execute</span>(<span class="str">"COPY result TO 'features.parquet' (FORMAT PARQUET)"</span>)
<div class="code-lang">python</div></code></pre>
</div>
<!-- APACHE -->
<div class="section" id="sec-apache">
<div class="section-header">
<div class="section-num">16 β€” APACHE STACK</div>
<h2>Apache <span class="accent4">Ecosystem</span></h2>
<p class="section-intro">These tools form the backbone of enterprise data engineering. Knowing when to reach for each β€” and when not to β€” is critical for system design interviews.</p>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>Tool</th><th>Role</th><th>ML Use Case</th><th>2026 Status</th></tr></thead>
<tbody>
<tr><td><strong>Apache Spark</strong></td><td>Distributed compute</td><td>Feature engineering at petabyte scale, Spark MLlib</td><td>βœ… Essential β€” use PySpark + Delta Lake</td></tr>
<tr><td><strong>Apache Kafka</strong></td><td>Event streaming</td><td>Real-time feature computation, online serving, training data streams</td><td>βœ… Essential β€” combine with Flink for streaming ML</td></tr>
<tr><td><strong>Apache Airflow</strong></td><td>Workflow orchestration</td><td>ML pipeline DAGs, retraining schedules, data quality checks</td><td>βœ… Still standard β€” Prefect/Dagster rising alternatives</td></tr>
<tr><td><strong>Snowflake</strong></td><td>Cloud data warehouse</td><td>Snowpark ML, feature stores, OLAP on structured data</td><td>βœ… Industry standard for enterprise analytics</td></tr>
<tr><td><strong>Apache Mahout</strong></td><td>Distributed ML</td><td>Legacy collaborative filtering, matrix factorisation</td><td>⚠️ Declining β€” replaced by Spark MLlib + Horovod</td></tr>
</tbody>
</table>
</div>
<h3>Airflow DAG for ML Retraining Pipeline</h3>
<pre><code><span class="kw">from</span> airflow <span class="kw">import</span> DAG
<span class="kw">from</span> airflow.operators.python <span class="kw">import</span> PythonOperator
<span class="kw">from</span> airflow.providers.apache.spark.operators.spark_submit <span class="kw">import</span> SparkSubmitOperator
<span class="kw">from</span> datetime <span class="kw">import</span> datetime, timedelta
default_args = {
<span class="str">"owner"</span>: <span class="str">"ml-team"</span>,
<span class="str">"retries"</span>: <span class="num">3</span>,
<span class="str">"retry_delay"</span>: timedelta(minutes=<span class="num">5</span>),
<span class="str">"email_on_failure"</span>: <span class="kw">True</span>,
<span class="str">"email"</span>: [<span class="str">"ml-alerts@company.com"</span>]
}
<span class="kw">with</span> <span class="fn">DAG</span>(
<span class="str">"weekly_churn_retrain"</span>,
default_args=default_args,
schedule_interval=<span class="str">"0 2 * * 1"</span>, <span class="cm"># every Monday at 2am</span>
start_date=datetime(<span class="num">2024</span>, <span class="num">1</span>, <span class="num">1</span>),
catchup=<span class="kw">False</span>
) <span class="kw">as</span> dag:
validate_data = <span class="fn">PythonOperator</span>(
task_id=<span class="str">"validate_input_data"</span>,
python_callable=<span class="kw">lambda</span>: <span class="fn">run_great_expectations_suite</span>(<span class="str">"churn_suite"</span>)
)
feature_eng = <span class="fn">SparkSubmitOperator</span>(
task_id=<span class="str">"compute_features"</span>,
application=<span class="str">"s3://scripts/feature_engineering.py"</span>,
conf={<span class="str">"spark.executor.memory"</span>: <span class="str">"8g"</span>, <span class="str">"spark.executor.cores"</span>: <span class="str">"4"</span>}
)
train_model = <span class="fn">PythonOperator</span>(
task_id=<span class="str">"train_xgboost"</span>,
python_callable=<span class="fn">train_and_log_to_mlflow</span>
)
validate_model = <span class="fn">PythonOperator</span>(
task_id=<span class="str">"validate_model_metrics"</span>,
python_callable=<span class="fn">compare_against_champion</span>
)
deploy = <span class="fn">PythonOperator</span>(
task_id=<span class="str">"deploy_to_sagemaker"</span>,
python_callable=<span class="fn">promote_challenger_to_champion</span>
)
validate_data >> feature_eng >> train_model >> validate_model >> deploy
<div class="code-lang">python</div></code></pre>
</div>
<!-- PROJECT 1 -->
<div class="section" id="sec-proj1">
<div class="section-header">
<div class="section-num">PROJECT 01</div>
<h2>ETL / <span class="accent">Warehousing</span> / OLAP</h2>
</div>
<div class="project-card">
<div class="project-header">
<div class="project-num">01</div>
<div class="project-meta">
<h3>E-Commerce Multi-Source Data Warehouse with Snowflake + Airflow</h3>
<p>ETL pipeline ingesting 5 source systems into a star-schema warehouse, serving OLAP dashboards via dbt + Metabase</p>
</div>
</div>
<div class="project-body">
<h4>Covers Topics</h4>
<div class="topic-pills">
<span class="pill">ETL / ELT</span><span class="pill-purple pill">Star Schema</span><span class="pill-yellow pill">Slowly Changing Dimensions</span><span class="pill">OLAP Cubes</span><span class="pill-red pill">Data Quality</span><span class="pill-purple pill">Airflow DAGs</span><span class="pill">dbt Transformations</span><span class="pill-yellow pill">Partitioning</span>
</div>
<h4>Dataset</h4>
<p>Combine the <strong>Brazilian E-Commerce (Olist) dataset</strong> from Kaggle (100k orders, 9 CSV files) with synthetic data from Faker representing web sessions and marketing touch-points. This simulates a real 5-source environment: orders DB, product catalogue, customer CRM, web analytics, and ad spend.</p>
<h4>Architecture</h4>
<pre><code>Sources: PostgreSQL (orders) + MongoDB (sessions) + S3 (ad spend CSV)
↓
Ingestion: Airbyte connectors β†’ S3 raw landing zone (JSON/CSV/Parquet)
↓
Transformation: dbt (Snowflake) β€” staging β†’ intermediate β†’ marts
↓
OLAP Layer: Snowflake + dbt metrics layer
↓
Serving: Metabase dashboards (Revenue, Cohort, Funnel KPIs)
<div class="code-lang">architecture</div></code></pre>
<h4>Star Schema Design</h4>
<pre><code><span class="cm">-- Fact Table</span>
<span class="kw">CREATE TABLE</span> fact_orders (
order_key BIGINT <span class="kw">PRIMARY KEY</span>,
customer_key BIGINT <span class="kw">REFERENCES</span> dim_customers,
product_key BIGINT <span class="kw">REFERENCES</span> dim_products,
date_key INT <span class="kw">REFERENCES</span> dim_date,
revenue NUMERIC(<span class="num">12</span>,<span class="num">2</span>),
quantity INT,
discount_pct NUMERIC(<span class="num">5</span>,<span class="num">2</span>),
shipping_days INT
);
<span class="cm">-- SCD Type 2 for customers (track historical changes)</span>
<span class="kw">CREATE TABLE</span> dim_customers (
customer_key BIGINT <span class="kw">GENERATED ALWAYS AS IDENTITY PRIMARY KEY</span>,
customer_id VARCHAR(<span class="num">50</span>), <span class="cm">-- natural key</span>
city VARCHAR(<span class="num">100</span>),
state VARCHAR(<span class="num">10</span>),
customer_tier VARCHAR(<span class="num">20</span>),
valid_from DATE <span class="kw">NOT NULL</span>,
valid_to DATE, <span class="cm">-- NULL = current record</span>
is_current BOOLEAN <span class="kw">DEFAULT TRUE</span>
);
<div class="code-lang">sql</div></code></pre>
<h4>Key dbt Transformation</h4>
<pre><code><span class="cm">-- models/marts/fct_orders_enriched.sql</span>
<span class="kw">WITH</span> orders <span class="kw">AS</span> (
<span class="kw">SELECT</span> * <span class="kw">FROM</span> {{ ref(<span class="str">'stg_orders'</span>) }}
),
customers <span class="kw">AS</span> (
<span class="kw">SELECT</span> * <span class="kw">FROM</span> {{ ref(<span class="str">'dim_customers'</span>) }} <span class="kw">WHERE</span> is_current = <span class="kw">TRUE</span>
),
cohort_revenue <span class="kw">AS</span> (
<span class="kw">SELECT</span>
c.customer_id,
<span class="fn">DATE_TRUNC</span>(<span class="str">'month'</span>, <span class="fn">MIN</span>(o.order_date)) <span class="kw">AS</span> cohort_month,
<span class="fn">SUM</span>(o.revenue) <span class="kw">AS</span> ltv_to_date
<span class="kw">FROM</span> orders o
<span class="kw">JOIN</span> customers c <span class="kw">USING</span> (customer_id)
<span class="kw">GROUP BY</span> c.customer_id
)
<span class="kw">SELECT</span>
o.*,
cr.cohort_month,
<span class="fn">SUM</span>(o.revenue) <span class="kw">OVER</span> (
<span class="kw">PARTITION BY</span> o.customer_id <span class="kw">ORDER BY</span> o.order_date
<span class="kw">ROWS UNBOUNDED PRECEDING</span>
) <span class="kw">AS</span> cumulative_ltv
<span class="kw">FROM</span> orders o
<span class="kw">LEFT JOIN</span> cohort_revenue cr <span class="kw">USING</span> (customer_id)
<div class="code-lang">sql</div></code></pre>
<h4>Key Findings</h4>
<p>Top-quartile customers (by LTV) account for 68% of revenue but only 12% of order volume. Cohort retention drops 40% after month 3 β€” a trigger for a re-engagement campaign feature. SCD Type 2 reveals 8% of customers changed tier within 6 months, a signal invisible in non-temporal designs.</p>
<h4>Methodologies</h4>
<p>ELT over ETL β€” push transformation to the warehouse (Snowflake handles scale). dbt enforces SQL-based transformation lineage. Great Expectations runs as Airflow tasks before each dbt model layer. Data contracts defined as YAML schemas in the repo.</p>
<h4>Tools Used</h4>
<div class="topic-pills">
<span class="pill">DuckDB (local dev)</span><span class="pill-purple pill">Snowflake (prod)</span><span class="pill-yellow pill">dbt Core</span><span class="pill">Airflow 2.8</span><span class="pill-red pill">Great Expectations</span><span class="pill-purple pill">Python 3.11</span><span class="pill">Pandas</span><span class="pill-yellow pill">Metabase</span>
</div>
<h4>Discussion</h4>
<p>SCD Type 2 adds storage overhead but is non-negotiable for ML β€” feature engineering must be point-in-time correct to avoid future leakage. For example, a churn model trained on a customer's current tier (not their tier at the time of the event) would be making predictions on data that didn't exist at decision time.</p>
<h4>Conclusions</h4>
<p>A well-designed star schema with SCD Type 2 dimensions reduces time-to-insight from days (ad-hoc SQL on raw tables) to minutes (indexed dimensional queries). The dbt lineage graph becomes your data dictionary, replacing tribal knowledge with machine-readable documentation.</p>
</div>
</div>
</div>
<!-- PROJECT 2 -->
<div class="section" id="sec-proj2">
<div class="section-header">
<div class="section-num">PROJECT 02</div>
<h2>EDA with <span class="accent2">Key Performance Metrics</span></h2>
</div>
<div class="project-card">
<div class="project-header">
<div class="project-num">02</div>
<div class="project-meta">
<h3>Churn Prediction EDA Engine with Automated KPI Dashboard</h3>
<p>End-to-end exploratory analysis of a telecom churn dataset with statistical hypothesis testing, feature importance ranking, and a live Streamlit KPI dashboard</p>
</div>
</div>
<div class="project-body">
<h4>Dataset</h4>
<p><strong>IBM Telco Customer Churn</strong> dataset (Kaggle) β€” 7,043 rows, 21 columns, 26.5% churn rate. Augment with synthetic records using CTGAN to reach 100k rows, simulating production scale.</p>
<h4>Statistical EDA Framework</h4>
<pre><code><span class="kw">import</span> pandas <span class="kw">as</span> pd
<span class="kw">import</span> numpy <span class="kw">as</span> np
<span class="kw">from</span> scipy <span class="kw">import</span> stats
<span class="kw">import</span> duckdb
<span class="cm"># Load via DuckDB for speed</span>
df = duckdb.<span class="fn">query</span>(<span class="str">"SELECT * FROM 'telco.parquet'"</span>).<span class="fn">df</span>()
<span class="cm"># Automated EDA report</span>
<span class="kw">def</span> <span class="fn">univariate_analysis</span>(df, target=<span class="str">"Churn"</span>):
report = {}
<span class="kw">for</span> col <span class="kw">in</span> df.columns:
<span class="kw">if</span> col == target: <span class="kw">continue</span>
<span class="kw">if</span> df[col].dtype == <span class="str">"object"</span>:
<span class="cm"># Chi-square test for categorical features vs target</span>
ct = pd.<span class="fn">crosstab</span>(df[col], df[target])
chi2, p, dof, _ = stats.chi2_contingency(ct)
cramer_v = np.<span class="fn">sqrt</span>(chi2 / (<span class="fn">len</span>(df) * (<span class="fn">min</span>(ct.shape) - <span class="num">1</span>)))
report[col] = {<span class="str">"test"</span>: <span class="str">"chi2"</span>, <span class="str">"p_value"</span>: p, <span class="str">"cramer_v"</span>: cramer_v}
<span class="kw">else</span>:
<span class="cm"># Point-biserial correlation for numeric vs binary target</span>
corr, p = stats.pointbiserialr(df[target] == <span class="str">"Yes"</span>, df[col].<span class="fn">fillna</span>(<span class="num">0</span>))
<span class="cm"># Mann-Whitney U test (non-parametric)</span>
churn_vals = df.<span class="fn">loc</span>[df[target]==<span class="str">"Yes"</span>, col].<span class="fn">dropna</span>()
no_churn_vals = df.<span class="fn">loc</span>[df[target]==<span class="str">"No"</span>, col].<span class="fn">dropna</span>()
_, p_mw = stats.mannwhitneyu(churn_vals, no_churn_vals, alternative=<span class="str">"two-sided"</span>)
report[col] = {<span class="str">"test"</span>: <span class="str">"biserial+MW"</span>, <span class="str">"p_value"</span>: p_mw, <span class="str">"correlation"</span>: corr}
<span class="kw">return</span> pd.<span class="fn">DataFrame</span>(report).T.<span class="fn">sort_values</span>(<span class="str">"p_value"</span>)
<div class="code-lang">python</div></code></pre>
<h4>Key Performance Metrics Implemented</h4>
<div class="table-wrap">
<table>
<thead><tr><th>KPI</th><th>Formula</th><th>Business Meaning</th></tr></thead>
<tbody>
<tr><td>Churn Rate</td><td>Churned / Total customers</td><td>Monthly retention health</td></tr>
<tr><td>Customer LTV</td><td>ARPU Γ— (1/Churn Rate)</td><td>Revenue per acquired customer</td></tr>
<tr><td>NRR (Net Revenue Retention)</td><td>(Start MRR + Expansion βˆ’ Churn) / Start MRR</td><td>Revenue momentum (target &gt;100%)</td></tr>
<tr><td>CAC Payback Period</td><td>CAC / (ARPU Γ— Gross Margin)</td><td>Months to recover acquisition cost</td></tr>
<tr><td>Product Adoption Score</td><td>Features Used / Total Features Γ— Frequency</td><td>Stickiness predictor for churn</td></tr>
</tbody>
</table>
</div>
<pre><code><span class="cm">-- SQL KPI computation (DuckDB / Snowflake)</span>
<span class="kw">WITH</span> monthly_metrics <span class="kw">AS</span> (
<span class="kw">SELECT</span>
<span class="fn">DATE_TRUNC</span>(<span class="str">'month'</span>, event_date) <span class="kw">AS</span> month,
<span class="fn">COUNT</span>(<span class="kw">DISTINCT</span> customer_id) <span class="kw">AS</span> active_customers,
<span class="fn">SUM</span>(revenue) <span class="kw">AS</span> mrr,
<span class="fn">COUNT</span>(<span class="kw">DISTINCT</span> <span class="kw">CASE</span> <span class="kw">WHEN</span> churn_flag = <span class="num">1</span> <span class="kw">THEN</span> customer_id <span class="kw">END</span>) <span class="kw">AS</span> churned
<span class="kw">FROM</span> fact_subscriptions
<span class="kw">GROUP BY</span> <span class="num">1</span>
)
<span class="kw">SELECT</span>
month,
mrr,
churned::FLOAT / active_customers <span class="kw">AS</span> churn_rate,
mrr / <span class="fn">NULLIF</span>(active_customers, <span class="num">0</span>) <span class="kw">AS</span> arpu,
<span class="cm">-- LTV = ARPU / Churn Rate</span>
(mrr / <span class="fn">NULLIF</span>(active_customers, <span class="num">0</span>)) /
<span class="fn">NULLIF</span>(churned::FLOAT / active_customers, <span class="num">0</span>) <span class="kw">AS</span> estimated_ltv
<span class="kw">FROM</span> monthly_metrics
<span class="kw">ORDER BY</span> month;
<div class="code-lang">sql</div></code></pre>
<h4>Feature Importance β€” SHAP Analysis</h4>
<pre><code><span class="kw">import</span> shap, xgboost <span class="kw">as</span> xgb
model = xgb.<span class="fn">XGBClassifier</span>(n_estimators=<span class="num">300</span>, max_depth=<span class="num">6</span>, use_label_encoder=<span class="kw">False</span>)
model.<span class="fn">fit</span>(X_train, y_train)
explainer = shap.<span class="fn">TreeExplainer</span>(model)
shap_values = explainer.<span class="fn">shap_values</span>(X_test)
<span class="cm"># Global importance</span>
shap.<span class="fn">summary_plot</span>(shap_values, X_test, plot_type=<span class="str">"bar"</span>)
<span class="cm"># Interaction effects</span>
shap_interaction = explainer.<span class="fn">shap_interaction_values</span>(X_test)
<span class="fn">print</span>(<span class="str">"Top interaction: tenure Γ— monthly_charges"</span>)
<div class="code-lang">python</div></code></pre>
<h4>Key Findings</h4>
<p>SHAP analysis reveals <strong>tenure is the single strongest churn predictor</strong> β€” customers in their first 3 months are 3.8Γ— more likely to churn. Month-to-month contracts contribute 45% of all churn volume despite representing 55% of contracts. Customers with Fibre Optic service and no TechSupport have a 41% churn rate vs 8% for those with support β€” a clear product intervention target.</p>
<h4>Conclusions</h4>
<p>An automated EDA framework with statistical hypothesis testing and SHAP explanations reduces the time from data to actionable insight by roughly 60% compared to manual notebook EDA. The Streamlit dashboard made the KPIs available to non-technical stakeholders, enabling product and marketing teams to act on churn signals in near-real-time.</p>
</div>
</div>
</div>
<!-- PROJECT 3 - CAPSTONE -->
<div class="section" id="sec-proj3">
<div class="section-header">
<div class="section-num">PROJECT 03 β€” CAPSTONE</div>
<h2>End-to-End <span class="accent3">ML Production</span> System</h2>
</div>
<div class="project-card">
<div class="project-header">
<div class="project-num">03</div>
<div class="project-meta">
<h3>Real-Time Fraud Detection ML System β€” From Raw Events to Serving</h3>
<p>Full MLOps pipeline: Kafka ingestion β†’ Spark feature engineering β†’ model training β†’ MLflow versioning β†’ FastAPI serving β†’ drift monitoring with Evidently</p>
</div>
</div>
<div class="project-body">
<h4>Covers Topics</h4>
<div class="topic-pills">
<span class="pill">Streaming ETL</span><span class="pill-purple pill">Feature Store</span><span class="pill-yellow pill">Class Imbalance</span><span class="pill">Model Registry</span><span class="pill-red pill">A/B Serving</span><span class="pill-purple pill">Drift Detection</span><span class="pill">Differential Privacy</span><span class="pill-yellow pill">Graph Features (Neo4j)</span><span class="pill">REST API</span><span class="pill-red pill">Data Lineage</span>
</div>
<h4>Dataset</h4>
<p><strong>IEEE-CIS Fraud Detection</strong> (Kaggle) β€” 590k transactions, 433 features, 3.5% fraud rate. Combined with <strong>PaySim synthetic dataset</strong> for the streaming simulation. Graph features derived from a Neo4j transaction graph (merchant–card–device relationships).</p>
<h4>System Architecture</h4>
<pre><code>β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ INGESTION LAYER β”‚
β”‚ POS Terminals β†’ Kafka (raw-transactions topic) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ STREAM PROCESSING (PySpark + Kafka Streams) β”‚
β”‚ - Parse / validate schema β”‚
β”‚ - Compute rolling aggregates (1h, 24h, 7d windows) β”‚
β”‚ - Join with merchant profile (Redis hot store) β”‚
β”‚ - Write to Delta Lake feature table β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ FEATURE STORE (Feast + DuckDB offline / Redis online) β”‚
β”‚ Point-in-time correct feature retrieval for training β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TRAINING PIPELINE (Airflow orchestrated) β”‚
β”‚ LightGBM + SMOTE + Optuna HPO + MLflow logging β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ SERVING (FastAPI + Triton Inference Server) β”‚
β”‚ p99 latency &lt; 15ms | 10k req/s throughput β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
<div class="code-lang">architecture</div></code></pre>
<h4>Handling Class Imbalance (3.5% Fraud)</h4>
<div class="math-block">
<div class="math-title">SMOTE β€” Synthetic Minority Over-sampling</div>
For each minority sample x_i, find k nearest neighbours.<br>
Generate synthetic sample: x_new = x_i + Ξ»(x_nn βˆ’ x_i) where Ξ» ∈ [0,1] random<br>
Use SMOTE-Tomek Links to simultaneously over-sample minority and under-sample majority boundary noise.<br><br>
<div class="math-title">Threshold Optimisation for Fraud</div>
Business cost: False Negative (missed fraud) = $500 | False Positive (blocked legit) = $3<br>
Optimal threshold Ο„* = argmin_Ο„ [FN(Ο„)Γ—500 + FP(Ο„)Γ—3]<br>
Use precision-recall curve, not ROC, for imbalanced problems.
</div>
<pre><code><span class="kw">from</span> imblearn.combine <span class="kw">import</span> SMOTETomek
<span class="kw">from</span> imblearn.over_sampling <span class="kw">import</span> SMOTENC <span class="cm"># handles categoricals</span>
<span class="kw">import</span> lightgbm <span class="kw">as</span> lgb
<span class="kw">import</span> optuna, mlflow
<span class="cm"># Handle mixed types with SMOTENC</span>
cat_idx = [df.<span class="fn">columns</span>.<span class="fn">get_loc</span>(c) <span class="kw">for</span> c <span class="kw">in</span> categorical_cols]
smt = <span class="fn">SMOTETomek</span>(smote=<span class="fn">SMOTENC</span>(categorical_features=cat_idx, k_neighbors=<span class="num">5</span>))
X_res, y_res = smt.<span class="fn">fit_resample</span>(X_train, y_train)
<span class="kw">def</span> <span class="fn">objective</span>(trial):
params = {
<span class="str">"n_estimators"</span>: trial.<span class="fn">suggest_int</span>(<span class="str">"n_estimators"</span>, <span class="num">200</span>, <span class="num">1000</span>),
<span class="str">"learning_rate"</span>: trial.<span class="fn">suggest_float</span>(<span class="str">"lr"</span>, <span class="num">0.01</span>, <span class="num">0.3</span>, log=<span class="kw">True</span>),
<span class="str">"num_leaves"</span>: trial.<span class="fn">suggest_int</span>(<span class="str">"leaves"</span>, <span class="num">16</span>, <span class="num">256</span>),
<span class="str">"scale_pos_weight"</span>: <span class="num">1</span> <span class="cm"># SMOTE handles balance</span>
}
model = lgb.<span class="fn">LGBMClassifier</span>(**params)
model.<span class="fn">fit</span>(X_res, y_res, eval_set=[(X_val, y_val)],
callbacks=[lgb.<span class="fn">early_stopping</span>(<span class="num">50</span>, verbose=<span class="kw">False</span>)])
<span class="cm"># Optimise on AUPRC β€” better for imbalanced</span>
<span class="kw">from</span> sklearn.metrics <span class="kw">import</span> average_precision_score
<span class="kw">return</span> <span class="fn">average_precision_score</span>(y_val, model.<span class="fn">predict_proba</span>(X_val)[:, <span class="num">1</span>])
study = optuna.<span class="fn">create_study</span>(direction=<span class="str">"maximize"</span>)
study.<span class="fn">optimize</span>(objective, n_trials=<span class="num">100</span>, n_jobs=-<span class="num">1</span>)
<div class="code-lang">python</div></code></pre>
<h4>Graph Feature Extraction (Neo4j)</h4>
<pre><code><span class="cm">// Cypher: extract fraud ring features via graph paths</span>
<span class="kw">MATCH</span> (card:Card)-[:USED_AT]->(merchant:Merchant)
<span class="kw">WHERE</span> card.id = $card_id
<span class="kw">WITH</span> card, <span class="fn">COLLECT</span>(merchant) <span class="kw">AS</span> merchants
<span class="kw">MATCH</span> (other_card:Card)-[:USED_AT]->(m:Merchant)
<span class="kw">WHERE</span> m <span class="kw">IN</span> merchants <span class="kw">AND</span> other_card &lt;&gt; card
<span class="kw">WITH</span> card,
<span class="fn">COUNT</span>(<span class="kw">DISTINCT</span> other_card) <span class="kw">AS</span> shared_merchant_cards,
<span class="fn">COUNT</span>(<span class="kw">DISTINCT</span> m) <span class="kw">AS</span> shared_merchants
<span class="kw">RETURN</span> card.id, shared_merchant_cards, shared_merchants,
shared_merchant_cards::FLOAT / shared_merchants <span class="kw">AS</span> concentration_score
<div class="code-lang">cypher</div></code></pre>
<h4>Model Serving β€” FastAPI</h4>
<pre><code><span class="kw">from</span> fastapi <span class="kw">import</span> FastAPI
<span class="kw">from</span> pydantic <span class="kw">import</span> BaseModel
<span class="kw">import</span> mlflow.pyfunc, numpy <span class="kw">as</span> np, time
app = <span class="fn">FastAPI</span>()
model = mlflow.pyfunc.<span class="fn">load_model</span>(<span class="str">"models:/fraud_detector/Production"</span>)
<span class="kw">class</span> <span class="cls">TransactionFeatures</span>(BaseModel):
amount: float
hour_of_day: int
days_since_first_tx: int
tx_count_1h: int
tx_amount_24h: float
shared_merchant_cards: int
<span class="cm"># ... other features</span>
<span class="cls">@app</span>.<span class="fn">post</span>(<span class="str">"/predict"</span>)
<span class="kw">async def</span> <span class="fn">predict_fraud</span>(tx: TransactionFeatures):
start = time.<span class="fn">perf_counter</span>()
features = np.<span class="fn">array</span>([[<span class="fn">getattr</span>(tx, f) <span class="kw">for</span> f <span class="kw">in</span> tx.<span class="fn">model_fields</span>]])
fraud_prob = model.<span class="fn">predict</span>(features)[<span class="num">0</span>]
latency_ms = (time.<span class="fn">perf_counter</span>() - start) * <span class="num">1000</span>
<span class="kw">return</span> {
<span class="str">"fraud_probability"</span>: <span class="fn">float</span>(fraud_prob),
<span class="str">"decision"</span>: <span class="str">"BLOCK"</span> <span class="kw">if</span> fraud_prob > <span class="num">0.42</span> <span class="kw">else</span> <span class="str">"ALLOW"</span>,
<span class="str">"latency_ms"</span>: latency_ms
}
<div class="code-lang">python</div></code></pre>
<h4>Key Findings</h4>
<p>Graph-derived features (shared merchant concentration score, device reuse rate) contributed 11 of the top 20 SHAP features β€” demonstrating that structural network information is orthogonal to transactional features. AUPRC improved from 0.71 (tabular only) to 0.84 (tabular + graph). The optimal decision threshold was 0.42, saving $2.1M in estimated fraud losses vs the default 0.5 threshold.</p>
<h4>Conclusions</h4>
<p>This capstone demonstrates that production ML is 80% data engineering and 20% modelling. The system handles 10k transactions/second with p99 latency under 15ms β€” achieved through Redis caching of graph features computed offline, Triton batching, and ONNX model export. The Airflow retraining DAG ensures the model is retrained weekly on fresh labelled data, preventing performance degradation from concept drift.</p>
</div>
</div>
</div>
<!-- PROJECTS 4 & 5 -->
<div class="section" id="sec-proj4">
<div class="section-header">
<div class="section-num">PROJECT 04</div>
<h2>Real-Time <span class="accent2">ML Pipeline</span></h2>
</div>
<div class="project-card">
<div class="project-header">
<div class="project-num">04</div>
<div class="project-meta">
<h3>Streaming Recommendation Engine β€” Kafka + Spark Structured Streaming + Pinecone</h3>
<p>Real-time personalised content recommendations using two-tower neural embeddings and approximate nearest neighbour search</p>
</div>
</div>
<div class="project-body">
<h4>Covers Topics</h4>
<div class="topic-pills">
<span class="pill">Two-Tower Architecture</span><span class="pill-purple pill">Contrastive Learning</span><span class="pill-yellow pill">Spark Structured Streaming</span><span class="pill">ANN Search</span><span class="pill-red pill">Online Feature Store</span><span class="pill-purple pill">Cold Start Problem</span>
</div>
<h4>Dataset</h4>
<p><strong>MovieLens 25M</strong> (GroupLens) β€” 25M ratings, 62k movies, 162k users. Simulate streaming events with Kafka producer replaying historical ratings at 5k events/second.</p>
<div class="math-block">
<div class="math-title">Two-Tower Model β€” InfoNCE Loss (Contrastive)</div>
L = βˆ’log [exp(sim(u, i⁺)/Ο„) / (exp(sim(u, i⁺)/Ο„) + Ξ£_j exp(sim(u, i_j⁻)/Ο„))]<br>
where sim(a,b) = cosine similarity, Ο„ = temperature (0.05–0.1), i⁺ = positive item<br>
User tower: embedding(user) β†’ MLP β†’ 128-dim unit vector<br>
Item tower: embedding(item) + metadata β†’ MLP β†’ 128-dim unit vector<br>
Retrieval: HNSW index on all item embeddings, query with user embedding
</div>
<pre><code><span class="kw">import</span> torch
<span class="kw">import</span> torch.nn <span class="kw">as</span> nn
<span class="kw">import</span> torch.nn.functional <span class="kw">as</span> F
<span class="kw">class</span> <span class="cls">TwoTowerModel</span>(nn.Module):
<span class="kw">def</span> <span class="fn">__init__</span>(self, n_users, n_items, emb_dim=<span class="num">64</span>, hidden=<span class="num">256</span>, out_dim=<span class="num">128</span>):
<span class="fn">super</span>().<span class="fn">__init__</span>()
self.user_emb = nn.<span class="fn">Embedding</span>(n_users, emb_dim)
self.item_emb = nn.<span class="fn">Embedding</span>(n_items, emb_dim)
self.user_tower = nn.<span class="fn">Sequential</span>(
nn.<span class="fn">Linear</span>(emb_dim, hidden), nn.<span class="fn">ReLU</span>(),
nn.<span class="fn">Linear</span>(hidden, out_dim)
)
self.item_tower = nn.<span class="fn">Sequential</span>(
nn.<span class="fn">Linear</span>(emb_dim, hidden), nn.<span class="fn">ReLU</span>(),
nn.<span class="fn">Linear</span>(hidden, out_dim)
)
<span class="kw">def</span> <span class="fn">forward</span>(self, user_ids, item_ids):
u = F.<span class="fn">normalize</span>(self.user_tower(self.user_emb(user_ids)), dim=-<span class="num">1</span>)
v = F.<span class="fn">normalize</span>(self.item_tower(self.item_emb(item_ids)), dim=-<span class="num">1</span>)
<span class="kw">return</span> u, v
<span class="kw">def</span> <span class="fn">infonce_loss</span>(u, v, temperature=<span class="num">0.07</span>):
<span class="str">"""In-batch negatives contrastive loss"""</span>
logits = (u @ v.T) / temperature <span class="cm"># (batch, batch)</span>
labels = torch.<span class="fn">arange</span>(<span class="fn">len</span>(u), device=u.device)
<span class="kw">return</span> F.<span class="fn">cross_entropy</span>(logits, labels)
<div class="code-lang">python</div></code></pre>
<h4>Key Findings</h4>
<p>The two-tower architecture achieves Recall@10 = 0.31 on held-out users β€” comparable to MF baselines at 10Γ— the serving speed (0.3ms vs 3ms) due to pre-computed item embeddings. Approximate Nearest Neighbour (HNSW) recall-precision trade-off at ef=200: 98.7% recall with 0.4ms search latency over 62k vectors.</p>
</div>
</div>
</div>
<div class="section" id="sec-proj5">
<div class="section-header">
<div class="section-num">PROJECT 05</div>
<h2>Synthetic <span class="accent">Benchmark</span> Suite</h2>
</div>
<div class="project-card">
<div class="project-header">
<div class="project-num">05</div>
<div class="project-meta">
<h3>Privacy-Preserving Synthetic Dataset Benchmark for Healthcare ML</h3>
<p>Generating synthetic EHR data with differential privacy guarantees and benchmarking utility-privacy trade-off across 5 synthesisers</p>
</div>
</div>
<div class="project-body">
<h4>Covers Topics</h4>
<div class="topic-pills">
<span class="pill">CTGAN / TVAE</span><span class="pill-purple pill">Differential Privacy</span><span class="pill-yellow pill">HIPAA Compliance</span><span class="pill">Membership Inference Attack</span><span class="pill-red pill">Utility Metrics</span><span class="pill-purple pill">Re-identification Risk</span>
</div>
<h4>Dataset</h4>
<p><strong>MIMIC-III Clinical Database Demo</strong> (PhysioNet) β€” 100 de-identified ICU patients. Extend to 10k synthetic patients using CTGAN + DP mechanisms.</p>
<div class="math-block">
<div class="math-title">Privacy-Utility Trade-off</div>
Utility = 1 βˆ’ |f(X_real) βˆ’ f(X_synth)| / f(X_real)<br>
where f is a downstream model's AUROC trained on each dataset.<br><br>
Re-identification Risk = max MIA accuracy (Membership Inference Attack)<br>
MIA accuracy &gt; 0.55 on a balanced test β†’ dataset leaks training membership.<br><br>
Privacy Budget Allocation: Ξ΅_total = Ξ΅_synthesis + Ξ΅_evaluation<br>
Use Ξ΅ = 1.0 (strong) for healthcare; utility loss β‰ˆ 3–8% AUROC.
</div>
<h4>Key Findings</h4>
<p>At Ξ΅=1.0, CTGAN-DP achieves 89% utility retention (AUROC: 0.83 real vs 0.74 synthetic) with MIA accuracy of 0.51 (effectively random). Without DP (Ξ΅=∞), utility rises to 98% but MIA accuracy hits 0.73 β€” a clear privacy failure. The benchmark demonstrates that Ξ΅=3.0 is a practical sweet spot: 94% utility with MIA accuracy 0.54.</p>
</div>
</div>
</div>
<!-- INTERVIEWS -->
<div class="section" id="sec-interviews">
<div class="section-header">
<div class="section-num">INTERVIEW PREP</div>
<h2>Big Tech <span class="accent3">Interview</span> Questions</h2>
<p class="section-intro">These questions reflect patterns from Google, Meta, Amazon, Microsoft, and Apple ML/Data Engineering rounds β€” covering coding, system design, case studies, and behavioural.</p>
</div>
<!-- Q1 -->
<div class="interview-card">
<div class="interview-header">
<span class="interview-type pill">Coding + System Design</span>
<span class="interview-company">Google / Meta</span>
</div>
<div class="interview-question">
"Design and implement a feature pipeline that computes, for each user, the following features at prediction time with <strong>p99 latency under 10ms</strong>: (1) number of purchases in the last 1h, 24h, 7d; (2) average transaction value in 30 days; (3) most frequent product category in the last 30 days. The pipeline must handle 50k events/second. How do you prevent point-in-time leakage in training vs serving?"
</div>
<div class="interview-body">
<h5>Coding Solution β€” Dual-Store Feature Architecture</h5>
<pre><code><span class="cm"># Online feature store with Redis for serving (&lt;1ms)</span>
<span class="kw">import</span> redis, json
<span class="kw">from</span> collections <span class="kw">import</span> defaultdict
<span class="kw">from</span> datetime <span class="kw">import</span> datetime, timedelta
r = redis.<span class="fn">Redis</span>(host=<span class="str">"redis"</span>, decode_responses=<span class="kw">True</span>)
<span class="kw">def</span> <span class="fn">update_user_features</span>(user_id: str, tx: dict):
<span class="str">"""Called on every Kafka event β€” O(log n) per update"""</span>
now = datetime.<span class="fn">utcnow</span>()
ts = now.<span class="fn">timestamp</span>()
pipe = r.<span class="fn">pipeline</span>(transaction=<span class="kw">False</span>) <span class="cm"># async pipeline</span>
<span class="cm"># Sorted sets β€” key: user_id:purchases, score: timestamp, value: amount</span>
pipe.<span class="fn">zadd</span>(<span class="str">f"tx:{user_id}"</span>, {<span class="str">f"{ts}:{tx['amount']}"</span>: ts})
<span class="cm"># TTL β€” auto-expire events older than 30 days</span>
pipe.<span class="fn">expire</span>(<span class="str">f"tx:{user_id}"</span>, <span class="num">30</span> * <span class="num">24</span> * <span class="num">3600</span>)
pipe.<span class="fn">execute</span>()
<span class="kw">def</span> <span class="fn">get_user_features</span>(user_id: str) -> dict:
<span class="str">"""Retrieve all time-window features atomically"""</span>
now = datetime.<span class="fn">utcnow</span>().<span class="fn">timestamp</span>()
windows = {<span class="str">"1h"</span>: <span class="num">3600</span>, <span class="str">"24h"</span>: <span class="num">86400</span>, <span class="str">"7d"</span>: <span class="num">604800</span>, <span class="str">"30d"</span>: <span class="num">2592000</span>}
pipe = r.<span class="fn">pipeline</span>()
<span class="kw">for</span> name, secs <span class="kw">in</span> windows.<span class="fn">items</span>():
pipe.<span class="fn">zrangebyscore</span>(<span class="str">f"tx:{user_id}"</span>, now - secs, now, withscores=<span class="kw">True</span>)
results = pipe.<span class="fn">execute</span>()
features = {}
<span class="kw">for</span> (name, _), entries <span class="kw">in</span> <span class="fn">zip</span>(windows.<span class="fn">items</span>(), results):
amounts = [<span class="fn">float</span>(e.<span class="fn">split</span>(<span class="str">":"</span>)[<span class="num">1</span>]) <span class="kw">for</span> e <span class="kw">in</span> entries]
features[<span class="str">f"tx_count_{name}"</span>] = <span class="fn">len</span>(amounts)
features[<span class="str">f"tx_sum_{name}"</span>] = <span class="fn">sum</span>(amounts)
features[<span class="str">f"tx_avg_{name}"</span>] = <span class="fn">sum</span>(amounts) / <span class="fn">max</span>(<span class="fn">len</span>(amounts), <span class="num">1</span>)
<span class="kw">return</span> features
<div class="code-lang">python</div></code></pre>
<h5>Point-in-Time Correctness (Training vs Serving)</h5>
<p>For serving, you query features at the current timestamp. For training, features must be computed as of the label timestamp β€” not the current time. This is solved with a <strong>point-in-time join</strong>: for each (user_id, label_timestamp) pair in your training set, replay the sorted-set query against an offline store (Delta Lake with timestamp partitioning) at exactly that timestamp.</p>
<pre><code><span class="cm">-- DuckDB point-in-time feature join</span>
<span class="kw">SELECT</span>
l.user_id,
l.label,
l.label_ts,
<span class="fn">COUNT</span>(*) <span class="kw">FILTER</span> (<span class="kw">WHERE</span> t.ts > l.label_ts - INTERVAL <span class="str">'1 hour'</span>) <span class="kw">AS</span> tx_count_1h,
<span class="fn">COUNT</span>(*) <span class="kw">FILTER</span> (<span class="kw">WHERE</span> t.ts > l.label_ts - INTERVAL <span class="str">'24 hours'</span>) <span class="kw">AS</span> tx_count_24h,
<span class="fn">AVG</span>(t.amount) <span class="kw">FILTER</span> (<span class="kw">WHERE</span> t.ts > l.label_ts - INTERVAL <span class="str">'30 days'</span>) <span class="kw">AS</span> avg_amount_30d
<span class="kw">FROM</span> labels l
<span class="kw">LEFT JOIN</span> transactions t <span class="kw">ON</span> t.user_id = l.user_id AND t.ts &lt; l.label_ts
<span class="kw">GROUP BY</span> l.user_id, l.label, l.label_ts
<div class="code-lang">sql</div></code></pre>
<h5>Why This Approach? What Are the Alternatives?</h5>
<p><strong>Why Redis sorted sets?</strong> O(log n) insert, O(log n + k) range query, automatic TTL expiry, atomic pipelined batch reads. Sub-millisecond at p99 under this load. Alternatives: (1) DynamoDB with TTL β€” simpler ops but higher latency (2–5ms); (2) Apache Flink stateful operators β€” better for exactly-once guarantees but higher operational complexity; (3) In-memory Hazelcast β€” fast but expensive for 50k/s with 30-day history.</p>
<h5>Case Study Scenario</h5>
<p>What if the sorted set for a high-frequency user (1M events in 30 days) becomes a Redis hotspot? Solution: shard by user_id modulo N (consistent hashing), use Redis Cluster for automatic sharding, and cap the sorted set size with ZREMRANGEBYSCORE on write. For the analytics path, materialise pre-aggregated hourly buckets in a separate key to reduce scan size from O(events) to O(buckets).</p>
<h5>Behavioural Pattern</h5>
<p>STAR format β€” Situation: "In my previous role, our recommendation system was using batch-computed features updated daily. We identified a 22% lift opportunity from real-time features but our Spark batch pipeline couldn't compute 1h windows. Task: Design a low-latency feature store. Action: Proposed a dual-store architecture β€” Redis for serving, Delta Lake for training. I led the implementation over 6 weeks. Result: p99 latency dropped from 80ms to 6ms, and real-time features contributed a 19% lift in CTR."</p>
</div>
</div>
<!-- Q2 -->
<div class="interview-card">
<div class="interview-header">
<span class="interview-type pill-purple pill">Conceptual + Tricky</span>
<span class="interview-company">Amazon / Apple</span>
</div>
<div class="interview-question">
"Your model's AUROC is 0.89 in offline evaluation but only 0.71 in production. You're confident the model code is correct. List all the data-related reasons this could happen and how you'd diagnose each. Then: why would you ever prefer a model with AUROC 0.75 over one with AUROC 0.89 for a fraud detection system?"
</div>
<div class="interview-body">
<h5>Systematic Diagnosis β€” Data-Side Root Causes</h5>
<div class="table-wrap">
<table>
<thead><tr><th>Root Cause</th><th>Mechanism</th><th>Diagnostic Test</th><th>Fix</th></tr></thead>
<tbody>
<tr><td><strong>Training-Serving Skew</strong></td><td>Feature computation differs between training (offline) and serving (online)</td><td>Log online features; compare distribution to training set using KS test</td><td>Use a unified feature store (Feast/Tecton)</td></tr>
<tr><td><strong>Data Leakage in Training</strong></td><td>Future information leaked into training features, inflating offline AUROC</td><td>Check feature timestamps vs label timestamp; audit feature engineering code</td><td>Point-in-time correct joins; strict temporal splits</td></tr>
<tr><td><strong>Concept Drift</strong></td><td>Real-world distribution shifted after training cutoff</td><td>Run Evidently drift report; compare monthly feature histograms</td><td>Retrain on recent data; add drift alerts</td></tr>
<tr><td><strong>Label Delay</strong></td><td>Ground truth labels arrive with lag (fraud confirmed weeks later), causing mislabelled recent training data</td><td>Plot label confirmation delay distribution</td><td>Delay training cutoff by label lag period</td></tr>
<tr><td><strong>Population Shift</strong></td><td>Training set over-represents certain segments (e.g., US users); prod traffic is global</td><td>Compare demographic distributions train vs prod</td><td>Stratified sampling; re-weighting</td></tr>
<tr><td><strong>Feedback Loop</strong></td><td>Model's past decisions changed the distribution of incoming data</td><td>Compare feature distributions before/after model deployment</td><td>Log counterfactual data; add exploration via Ξ΅-greedy</td></tr>
</tbody>
</table>
</div>
<h5>Why Prefer AUROC 0.75 Over 0.89?</h5>
<p>AUROC is a <strong>rank-based metric</strong> β€” it tells you how well the model separates classes but nothing about the operational point on the precision-recall curve. A model with AUROC 0.75 might have:</p>
<ul>
<li><strong>Better calibration</strong> β€” if probabilities are well-calibrated, threshold selection is stable and interpretable. The 0.89 model may be perfectly discriminative but miscalibrated (all outputs cluster near 0 or 1), making threshold selection brittle.</li>
<li><strong>Lower latency</strong> β€” a shallower model (lower AUROC) that runs in 0.5ms may be preferred over a deep ensemble (0.89 AUROC) taking 50ms if the use case is transaction blocking at checkout.</li>
<li><strong>Better fairness</strong> β€” if the 0.89 model achieves its performance by exploiting a demographic proxy feature, regulatory and reputational risk may outweigh the AUROC gain.</li>
<li><strong>More stable over time</strong> β€” a simpler model with lower AUROC may degrade more gracefully under distribution shift than an over-fitted complex model.</li>
</ul>
<div class="math-block">
<div class="math-title">Expected Cost Minimisation (Better than AUROC for Business)</div>
E[Cost] = FN Γ— cost_fn + FP Γ— cost_fp<br>
For fraud: cost_fn = average fraud amount ($150) | cost_fp = customer friction ($3)<br>
Optimal decision: flag if P(fraud|x) &gt; cost_fp / (cost_fp + cost_fn) = 3/153 β‰ˆ 0.02<br>
This is far more actionable than optimising AUROC.
</div>
<h5>Behavioural Pattern</h5>
<p>Use this to demonstrate independent thinking: "In a previous project, a junior engineer proposed deploying a model with AUROC 0.91 over our production model at 0.83. I asked to see the calibration plots and confusion matrix at our operational threshold. The new model had a 40% higher false-positive rate at the same recall level β€” which in our user-facing context meant 40% more incorrectly blocked legitimate transactions. We decided not to deploy it and instead used Platt scaling to calibrate both models. The recalibrated 0.83 model outperformed the 0.91 model on the business KPI."</p>
</div>
</div>
<!-- Q3 -->
<div class="interview-card">
<div class="interview-header">
<span class="interview-type pill-yellow pill">Real-World Scenario</span>
<span class="interview-company">Microsoft / Netflix</span>
</div>
<div class="interview-question">
"You discover that 15% of your training dataset for a medical diagnosis model contains mislabelled records due to a bug in your ETL pipeline. The model is already in production. Walk me through the full remediation plan, and write the SQL/Python to identify and quantify the scope of the corruption."
</div>
<div class="interview-body">
<h5>Incident Remediation Plan</h5>
<pre><code><span class="kw">import</span> pandas <span class="kw">as</span> pd
<span class="kw">import</span> duckdb
<span class="kw">from</span> datetime <span class="kw">import</span> datetime
<span class="kw">import</span> logging
logger = logging.<span class="fn">getLogger</span>(<span class="str">"label-audit"</span>)
<span class="kw">def</span> <span class="fn">scope_label_corruption</span>(
raw_db_path: str, <span class="cm"># original source of truth</span>
pipeline_output_path: str, <span class="cm"># ETL output with bug</span>
bug_introduced_ts: str <span class="cm"># timestamp when bug was deployed</span>
) -> dict:
<span class="str">"""
Step 1: Quantify the blast radius.
Compare raw labels to ETL output labels for records processed after bug_ts.
"""</span>
con = duckdb.<span class="fn">connect</span>()
result = con.<span class="fn">execute</span>(<span class="str">f"""
WITH source AS (
SELECT record_id, label AS true_label
FROM read_parquet('{raw_db_path}')
),
pipeline AS (
SELECT record_id, label AS etl_label, processed_at
FROM read_parquet('{pipeline_output_path}')
WHERE processed_at >= TIMESTAMP '{bug_introduced_ts}'
)
SELECT
COUNT(*) AS affected_records,
SUM(CASE WHEN source.true_label != pipeline.etl_label THEN 1 ELSE 0 END) AS mislabelled,
AVG(CASE WHEN source.true_label != pipeline.etl_label THEN 1.0 ELSE 0.0 END) AS mislabel_rate,
-- Stratify by class to assess bias direction
source.true_label,
COUNT(*) AS class_count
FROM source JOIN pipeline USING (record_id)
GROUP BY source.true_label
ORDER BY mislabel_rate DESC
"""</span>).<span class="fn">df</span>()
logger.<span class="fn">critical</span>(<span class="str">f"LABEL CORRUPTION AUDIT: {result}"</span>)
<span class="kw">return</span> result.<span class="fn">to_dict</span>()
<span class="cm"># Step 2: Shadow mode β€” run old and new model in parallel</span>
<span class="cm"># Step 3: Retrain on clean labels β€” do NOT use any records from bug window</span>
<span class="cm"># Step 4: If model cannot be rolled back immediately, implement uncertainty gating:</span>
<span class="cm"># If model entropy &gt; threshold, route to human review instead of auto-decision</span>
<div class="code-lang">python</div></code></pre>
<h5>Full Remediation Sequence</h5>
<ul>
<li><strong>T+0 (discovery):</strong> Pause any automated retraining pipelines to prevent further contamination. Flag the corrupted model version in MLflow with a "COMPROMISED" tag.</li>
<li><strong>T+0 (production):</strong> For medical diagnosis specifically β€” if the model affects clinical decisions, escalate to the Clinical Safety Officer immediately. Consider enabling human-in-the-loop review for all predictions until the model is replaced. This is an EU AI Act Article 9 requirement for high-risk medical AI.</li>
<li><strong>T+1 (scope):</strong> Run the SQL audit above. Determine: which classes are disproportionately mislabelled? If false negatives for a dangerous condition are elevated, the risk is asymmetric.</li>
<li><strong>T+2 (fix source):</strong> Fix the ETL bug. Back-fill the pipeline for all affected records. Validate the fix with the diff query above β€” expect 0 mismatches.</li>
<li><strong>T+3 (retrain):</strong> Retrain on clean data. Use stratified k-fold to validate label quality (if any contamination remains, cross-validation variance will be elevated).</li>
<li><strong>T+4 (validate):</strong> Before replacing production model, run shadow deployment for 48h. Compare prediction distributions β€” a large shift indicates the clean model learned different signal.</li>
<li><strong>T+7 (post-mortem):</strong> Add a label consistency check as a Great Expectations suite step in the ETL DAG. Alert on mislabel rate &gt; 0.5%.</li>
</ul>
<h5>Behavioural Pattern</h5>
<p>Demonstrate ownership: "I would not wait for escalation to act β€” I would immediately quarantine the contaminated model version in the registry and notify the medical team. My philosophy is to over-communicate early in an incident, even if the full scope is unclear. In a similar incident at a prior role, our delay in communication led to 3 days of bad model serving. I learned that a 30-minute early alert β€” even with incomplete information β€” is always preferable to a 3-day wait for a perfect root cause analysis."</p>
</div>
</div>
</div>
<!-- RESOURCES -->
<div class="section" id="sec-resources">
<div class="section-header">
<div class="section-num">RESOURCES</div>
<h2>Books, Papers <span class="accent4">&amp; Courses</span></h2>
<p class="section-intro">Curated to the highest-quality resources β€” the ones actually cited in production teams and PhD dissertations alike.</p>
</div>
<h3>Essential Books</h3>
<ul class="resource-list">
<li><span class="res-type res-book">Book</span><div><strong>Designing Machine Learning Systems</strong> β€” Chip Huyen (O'Reilly 2022) β€” The definitive guide to production ML, covers feature stores, data quality, and deployment end-to-end.</div></li>
<li><span class="res-type res-book">Book</span><div><strong>Fundamentals of Data Engineering</strong> β€” Reis & Housley (O'Reilly 2022) β€” Best overview of the full data stack from ingestion to serving.</div></li>
<li><span class="res-type res-book">Book</span><div><strong>High Performance Spark</strong> β€” Karau & Warren (O'Reilly) β€” Internals, tuning, and optimisation of PySpark pipelines.</div></li>
<li><span class="res-type res-book">Book</span><div><strong>The Elements of Statistical Learning</strong> β€” Hastie, Tibshirani, Friedman (Free PDF: web.stanford.edu/~hastie/ElemStatLearn/) β€” Mathematical foundations essential for every ML engineer.</div></li>
<li><span class="res-type res-book">Book</span><div><strong>Data Pipelines Pocket Reference</strong> β€” Densmore (O'Reilly 2021) β€” Practical guide covering Kafka, Airflow, Spark.</div></li>
<li><span class="res-type res-book">Book</span><div><strong>Responsible Data Science</strong> β€” Schelter & Stoyanovich (MIT Press) β€” Ethics, fairness, and governance with code examples.</div></li>
</ul>
<h3>Landmark Papers</h3>
<ul class="resource-list">
<li><span class="res-type res-paper">Paper</span><div><strong>Datasheets for Datasets</strong> β€” Gebru et al. (2018) β€” arxiv.org/abs/1803.09010 β€” Standard for dataset documentation. Read before publishing any dataset.</div></li>
<li><span class="res-type res-paper">Paper</span><div><strong>Data Management Challenges in Production ML</strong> β€” Sculley et al. (NIPS 2015) β€” "Hidden Technical Debt in ML Systems" β€” Essential reading on ML engineering pitfalls.</div></li>
<li><span class="res-type res-paper">Paper</span><div><strong>Differential Privacy: A Survey of Results</strong> β€” Dwork (2008) β€” Foundational DP theory with mathematical proofs.</div></li>
<li><span class="res-type res-paper">Paper</span><div><strong>SMOTE: Synthetic Minority Over-sampling Technique</strong> β€” Chawla et al. (JAIR 2002) β€” Original SMOTE paper, still the most cited class imbalance technique.</div></li>
<li><span class="res-type res-paper">Paper</span><div><strong>Attention Is All You Need</strong> β€” Vaswani et al. (2017) β€” The transformer architecture that powers every modern NLP feature pipeline.</div></li>
<li><span class="res-type res-paper">Paper</span><div><strong>Lakehouse: A New Generation of Open Platforms</strong> β€” Zaharia et al. (CIDR 2021) β€” Foundational paper for Delta Lake / Iceberg / Hudi architectures.</div></li>
</ul>
<h3>Courses & Learning Paths</h3>
<ul class="resource-list">
<li><span class="res-type res-course">Course</span><div><strong>mlops-zoomcamp</strong> β€” github.com/DataTalksClub/mlops-zoomcamp β€” Free, hands-on MLOps with MLflow, Prefect, and FastAPI. Highest ROI course in this space.</div></li>
<li><span class="res-type res-course">Course</span><div><strong>Full Stack Deep Learning</strong> β€” fullstackdeeplearning.com β€” From data pipelines to LLM deployment. Free online lectures.</div></li>
<li><span class="res-type res-course">Course</span><div><strong>Stanford CS329S: ML Systems Design</strong> β€” stanford-cs329s.github.io β€” Chip Huyen's course. Lecture notes freely available.</div></li>
<li><span class="res-type res-course">Course</span><div><strong>dbt Fundamentals</strong> β€” courses.getdbt.com β€” Free, the best way to learn dbt for data transformation.</div></li>
<li><span class="res-type res-docs">Docs</span><div><strong>Apache Spark Official Documentation</strong> β€” spark.apache.org/docs/latest β€” Internals, tuning guide, and PySpark API.</div></li>
<li><span class="res-type res-docs">Docs</span><div><strong>DuckDB Documentation</strong> β€” duckdb.org/docs β€” Especially the SQL extensions and Parquet/Arrow integration.</div></li>
</ul>
<div class="callout callout-tip">
<div class="callout-icon">🎯</div>
<div class="callout-body">
<strong>Learning Path Recommendation (6 months)</strong>
<p>Month 1–2: Pandas β†’ DuckDB β†’ SQL mastery (window functions, CTEs). Month 3: Airflow + dbt + build Project 1. Month 4: Spark + Kafka + build Project 2 & 3. Month 5: MLflow + model serving + build Projects 4 & 5. Month 6: Mock interviews, contribute an open-source fix to DuckDB/dbt, publish your capstone writeup on Medium.</p>
</div>
</div>
</div>
</main>
<script>
function show(id) {
// Hide all sections
document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
// Show target
var target = document.getElementById('sec-' + id);
if (target) target.classList.add('active');
// Update nav
document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
event.currentTarget.classList.add('active');
// Scroll main to top
document.getElementById('main').scrollTo({top: 0, behavior: 'smooth'});
}
</script>
</body>
</html>