DOCODIVE
Advanced Free Learning Path

Machine Learning Advanced: Deep Learning, NLP & Deployment

Master the frontier — gradient boosting internals, neural networks, transformers, RAG, vector databases, causal ML, MLOps, and ship a production ML system. This is the full ML engineering skill set.

10–14 weeks 40 lessons 1 capstone ML Intermediate required
Start Learning
01

Gradient Boosting Internals

28 min
What you'll learn
  • Understand boosting math
  • Learn loss gradient descent
  • See how trees stack

Gradient boosting trains trees sequentially — each new tree fits the NEGATIVE GRADIENT of the loss (the 'residuals' the previous trees got wrong). The final prediction is the sum of all trees' outputs. This is literally gradient descent in function space: instead of updating weights, you add trees that move predictions down the loss surface. Understanding this math makes every XGBoost parameter make sense.

boosting.py
# Pseudocode of gradient boosting
# for each tree:
#    residuals = -gradient(loss, current_pred)
#    tree = fit(X, residuals)
#    pred += learning_rate * tree(X)
Live Preview
Gradient Boosting Internals
T1
T2
T3
Sum
🔎 Important: Learning rate = step size. Small steps + many trees = the best general recipe for tabular data.
Try it yourself

What does each new boosting tree fit?

Loss gradient.
The negative gradient (residuals) of the loss function.
02

XGBoost Advanced Parameters

26 min
What you'll learn
  • Master tree and regularization params
  • Control overfitting
  • Tune learning rate

Beyond n_estimators and learning_rate, XGBoost has critical knobs: max_depth (tree complexity), subsample (row fraction per tree), colsample_bytree (feature fraction), reg_lambda/reg_alpha (L2/L1 regularization), min_child_weight (minimum leaf weight). Together they control the bias-variance trade-off. The standard recipe: small learning rate (0.05-0.1), shallow trees (depth 3-6), and early stopping on a validation set.

xgboost.py
import xgboost as xgb
model = xgb.XGBClassifier(
    n_estimators=1000,
    learning_rate=0.05,
    max_depth=4,
    subsample=0.8,
    colsample_bytree=0.8,
    reg_lambda=1.0,
    early_stopping_rounds=50
)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)])
Live Preview
XGBoost Advanced Parameters
max_depth
subsample
colsample
✓ Best Practice: Early stopping is your best friend — it stops training when validation stops improving, preventing overfit automatically.
Try it yourself

What does subsample=0.8 do?

Rows per tree.
Each tree uses 80% of training rows, reducing overfitting.
03

LightGBM & CatBoost

26 min
What you'll learn
  • Compare modern boosting libraries
  • Handle categorical features natively
  • Pick the right tool

LightGBM uses leaf-wise growth and histogram binning — faster training, often better on large data. CatBoost handles categorical features natively (no one-hot needed) and is robust to target leakage with ordered boosting. In practice: try all three, pick by cross-validation. Each has strengths, but for categorical-heavy data CatBoost often wins with zero encoding effort.

libs.py
from lightgbm import LGBMClassifier
from catboost import CatBoostClassifier

lgb = LGBMClassifier(n_estimators=500, learning_rate=0.05)
cat = CatBoostClassifier(cat_features=['city','job'], verbose=0)
# Train both, compare by CV
Live Preview
LightGBM & CatBoost
XGBoost
LightGBM
CatBoost
💡 Tip: CatBoost's cat_features removes the one-hot headache — pass your categorical columns directly.
Try it yourself

Which boosting lib handles categories natively?

Cat.
CatBoost.
04

Neural Networks from an ML Perspective

28 min
What you'll learn
  • Understand MLP as universal approximator
  • Learn backprop intuition
  • Connect to classical ML

A neural network is just stacked logistic regressions with non-linearities in between. Where linear models learn one decision boundary, MLPs learn many, composed into complex shapes. Backprop is the chain rule — it computes how each weight affects loss and updates them. The key ML insight: neural nets are powerful but data-hungry; gradient boosting often beats them on small tabular data.

mlp.py
import torch
import torch.nn as nn

mlp = nn.Sequential(
    nn.Linear(50, 128), nn.ReLU(),
    nn.Linear(128, 64), nn.ReLU(),
    nn.Linear(64, 2)
)
print(mlp)
Live Preview
Neural Networks from an ML Perspective
🔎 Important: Rule of thumb: tabular data < 10k rows → gradient boosting wins. Neural nets shine on images, text, and massive tabular data.
Try it yourself

When is a neural net preferable to gradient boosting?

Data type/size.
Images, text, audio, or very large datasets.
05

Convolutional Neural Networks for ML Engineers

28 min
What you'll learn
  • Build CNNs for images
  • Understand conv/pool layers
  • Apply transfer learning

CNNs are the standard for image ML. Convolution filters slide over the image detecting patterns; pooling downsamples; and a classifier head outputs predictions. In practice, you rarely train from scratch — you load a pre-trained backbone (ResNet, EfficientNet) and fine-tune on your task. This transfer learning gets state-of-the-art accuracy with hundreds, not millions, of images.

cnn.py
import torch.nn as nn
from torchvision import models

model = models.resnet18(pretrained=True)
model.fc = nn.Linear(512, 10)  # replace classifier head
for param in model.parameters(): param.requires_grad = False
model.fc.requires_grad = True
Live Preview
Convolutional Neural Networks for ML Engineers
✓ Best Practice: Transfer learning: freeze the pre-trained backbone, train only the new head. 90% of image ML is this pattern.
Try it yourself

Why freeze the backbone?

Prevent overfit on small data.
Backbone learned general features; freezing keeps them and adapts only the head.
06

Sequence Models for ML

28 min
What you'll learn
  • Process sequences with RNN/LSTM
  • Handle variable-length input
  • Apply to time series and text

Sequences — text, sensor readings, time series — need models that respect order. RNNs maintain hidden state across steps; LSTMs add gating for long-range memory. The ML angle: sequences often become features for downstream prediction (encode a sequence, then classify). In production, embeddings + attention have largely replaced pure RNNs, but understanding sequence modeling is foundational.

sequence.py
import torch.nn as nn

lstm = nn.LSTM(input_size=10, hidden_size=32, num_layers=2, batch_first=True)
# output: (batch, seq_len, hidden)
output, (h, c) = lstm(x)
print(output.shape)
Live Preview
Sequence Models for ML
x1
x2
x3
h
💡 Tip: The final hidden state summarizes the whole sequence — use it as a feature for classification.
Try it yourself

What does the hidden state represent?

Memory.
The network's memory of what it has seen so far in the sequence.
07

Transformers for ML

30 min
What you'll learn
  • Understand self-attention
  • Use pre-trained transformers
  • Fine-tune for custom tasks

Transformers process all tokens in parallel via self-attention, capturing long-range dependencies in one step. The ML angle: load a pre-trained model (BERT for understanding, GPT for generation), fine-tune on your labeled data, and you have state-of-the-art performance with little effort. Fine-tuning = train the model on your task for a few epochs with a small learning rate.

transformer.py
from transformers import AutoModelForSequenceClassification, Trainer
model = AutoModelForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=5)
# Fine-tune with Trainer on labeled data
Live Preview
Transformers for ML
Encoder
Self-Attention
Decoder
✓ Best Practice: Fine-tuning beats training from scratch by orders of magnitude on small data — always start pre-trained.
Try it yourself

What is fine-tuning?

Adapt pre-trained.
Adapting a pre-trained model to your task with a small amount of training.
08

Training Deep Models Efficiently

26 min
What you'll learn
  • Use GPUs and mixed precision
  • Apply gradient accumulation
  • Manage batch size

Deep models are compute-hungry. GPUs parallelize matrix math (10-100x speedup). Mixed precision (fp16) doubles throughput on modern GPUs with negligible accuracy loss. Gradient accumulation lets you simulate large batches on limited memory. Batch size affects convergence — larger batches train faster but may need learning rate scaling. These are the practical skills that separate experimentation from production training.

efficient.py
from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()
with autocast():
    output = model(x)
    loss = criterion(output, y)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
Live Preview
Training Deep Models Efficiently
Loss
Epoch
💡 Tip: Mixed precision is nearly free speed — enable it in your training loop with GradScaler.
Try it yourself

What does mixed precision use?

fp16.
16-bit floats for most ops, 32-bit where precision matters.
09

Learning to Rank

28 min
What you'll learn
  • Understand ranking vs classification
  • Use LambdaMART/ListNet
  • Build search and recommendation ranking

Ranking predicts ORDER, not classes. In search and recommendations, you don't care if an item is 'relevant' absolutely — you care that the most relevant item is FIRST. Pointwise (score each item), pairwise (which of two is better), and listwise (order the whole list) are the three approaches. LambdaMART (LightGBM with ranking objective) is the industry standard for search ranking.

ranking.py
import lightgbm as lgb
model = lgb.LGBMRanker(objective='lambdarank')
model.fit(X_train, y_train, group=query_groups)
ranking = model.predict(X_test)
Live Preview
Learning to Rank
1st
2nd
3rd
🔎 Important: Ranking is everywhere — search, feeds, recommendations. The key is query grouping: items for the same query form a group.
Try it yourself

What does 'group' mean in ranking?

Query.
All items belonging to the same query/user — ranked within the group.
10

Gaussian Processes

28 min
What you'll learn
  • Understand probabilistic prediction
  • Learn uncertainty estimation
  • Apply to small-data regression

Gaussian Processes (GPs) predict a DISTRIBUTION, not just a point — giving both a mean and uncertainty. They're non-parametric (grow with data), smooth, and perfect for small datasets where you need calibrated uncertainty — Bayesian optimization, experimental design, engineering optimization. The catch: they scale badly (O(n³)), so they cap out around a few thousand points.

gp.py
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF

model = GaussianProcessRegressor(kernel=RBF())
model.fit(X, y)
y_mean, y_std = model.predict(X_test, return_std=True)
print('Prediction ± uncertainty:', y_mean[0], '±', y_std[0])
Live Preview
Gaussian Processes
💡 Tip: GPs shine when data is small and uncertainty matters — they're the engine inside Bayesian optimization.
Try it yourself

What's the main limitation of Gaussian Processes?

Scaling.
O(n³) complexity — impractical beyond a few thousand points.
11

Bayesian Methods in ML

26 min
What you'll learn
  • Understand Bayesian reasoning
  • Use probabilistic programming
  • Quantify uncertainty everywhere

Bayesian ML treats parameters as distributions, not fixed values — you get full uncertainty, not point estimates. Bayes' theorem: posterior ∝ likelihood × prior. Probabilistic programming (PyMC, Stan) makes this practical. The benefit: calibrated uncertainty, better decisions under limited data, and principled regularization (the prior). It's the mathematically honest approach, at the cost of computation.

bayesian.py
import pymc as pm
with pm.Model() as model:
    theta = pm.Beta('theta', alpha=2, beta=2)
    y = pm.Bernoulli('y', p=theta, observed=data)
    trace = pm.sample(1000)
Live Preview
Bayesian Methods in ML
Beta(2,2)
Prior
Posterior
🔎 Important: Priors are your regularization in Bayesian ML — they encode what you believe before seeing data.
Try it yourself

What does the prior represent?

Before data.
Your belief about parameters before observing data.
12

Online Learning

24 min
What you'll learn
  • Learn from streaming data
  • Update models incrementally
  • Handle concept drift

Online learning updates the model one sample (or mini-batch) at a time, instead of retraining on everything. It's essential for streaming data — clickstreams, sensor feeds, live dashboards — where retraining is too slow and data arrives continuously. Algorithms like SGD, Vowpal Wabbit, and River (Python) are designed for this. Concept drift — when patterns change over time — is the central challenge.

online.py
from river import linear_model, metrics
model = linear_model.LogisticRegression()
for x, y in stream:
    model.learn_one(x, y)  # update incrementally
    pred = model.predict_one(x_new)
Live Preview
Online Learning
sample₁
update
sample₂
💡 Tip: Online learning is for when the world changes under you — it adapts continuously instead of retraining.
Try it yourself

What is concept drift?

Changing patterns.
When the data distribution changes over time, making old models stale.
13

Multi-Armed Bandits

26 min
What you'll learn
  • Understand explore vs exploit
  • Learn epsilon-greedy and UCB
  • Apply to recommendations/experiments

Multi-armed bandits are the explore-exploit framework: try options (explore) to learn which is best, while favoring the best so far (exploit). Epsilon-greedy explores randomly ε of the time; UCB explores options with high uncertainty; Thompson sampling is the Bayesian version. Applications: A/B testing that adapts, news recommendation, ad placement. Bandits continuously optimize instead of running one fixed experiment.

bandit.py
import numpy as np
def epsilon_greedy(epsilon, values):
    if np.random.rand() < epsilon:
        return np.random.choice(len(values))  # explore
    return np.argmax(values)  # exploit
Live Preview
Multi-Armed Bandits
Explore
Exploit
Learn
💡 Tip: Bandits beat static A/B testing when you need to continuously optimize — they learn AND earn simultaneously.
Try it yourself

What trade-off do bandits balance?

Try vs use.
Exploration (learning) vs exploitation (using best known).
14

Graph Machine Learning

30 min
What you'll learn
  • Represent data as graphs
  • Learn node embeddings
  • Apply graph neural networks

Graph ML handles relational data — social networks, molecules, knowledge graphs, recommendation graphs — where connections matter as much as features. Node embeddings (node2vec) learn vector representations that preserve graph structure. Graph Neural Networks (GCN, GAT) pass messages between connected nodes, combining node features with neighbors'. This is the frontier for fraud rings, drug discovery, and social analysis.

graph.py
import torch_geometric.nn as gnn
from torch_geometric.nn import GCNConv
class GCN(nn.Module):
    def __init__(self): super().__init__()
        self.conv1 = GCNConv(16, 32)
        self.conv2 = GCNConv(32, 7)
    def forward(self, data):
        x = self.conv1(data.x, data.edge_index)
        return self.conv2(x.relu(), data.edge_index)
Live Preview
Graph Machine Learning
🔎 Important: Graphs capture what tabular data can't: the relationships between entities are often the strongest signal.
Try it yourself

Name one graph ML application.

Relationships.
Fraud detection (transaction networks), social recommendations, molecule property prediction.
15

Metric Learning

26 min
What you'll learn
  • Learn similarity functions
  • Use triplet/contrastive loss
  • Build face recognition/search

Metric learning trains models to output embeddings where similar items are close and dissimilar items are far apart — even for classes never seen in training. Triplet loss (anchor, positive, negative) and contrastive loss are the standard objectives. Applications: face recognition, image retrieval, few-shot learning. The key idea: learn a distance metric, not a classifier.

metric.py
import torch
import torch.nn.functional as F
def triplet_loss(anchor, positive, negative, margin=0.2):
    pos_dist = F.pairwise_distance(anchor, positive)
    neg_dist = F.pairwise_distance(anchor, negative)
    return F.relu(pos_dist - neg_dist + margin).mean()
Live Preview
Metric Learning
Anchor
Positive (close)
Negative (far)
💡 Tip: Metric learning enables zero-shot recognition — recognize faces never seen in training by their embedding.
Try it yourself

What does the margin in triplet loss do?

Separation.
Enforces a minimum distance between positive and negative pairs.
16

Self-Supervised Learning

28 min
What you'll learn
  • Learn without labels
  • Use pretext tasks
  • Leverage unlabeled data

Self-supervised learning creates its own labels from unlabeled data — predict a masked word in a sentence, predict a rotated image's angle, predict the next frame. The model learns rich representations doing this 'pretext task', then transfers to real tasks with few labels. This is how GPT and BERT were pre-trained. It's the answer to the bottleneck of expensive labels.

selfsup.py
# Pretext task: predict masked token
sentence = 'The cat sat on the [MASK].'
# Model learns to predict 'mat' from context
# This unsupervised task teaches language understanding
Live Preview
Self-Supervised Learning
No labels needed
✓ Best Practice: Self-supervision is the secret behind modern AI — pre-train on unlabeled data, fine-tune on tiny labeled data.
Try it yourself

Why is self-supervision powerful?

Labels expensive.
It learns from unlimited unlabeled data, removing the labeling bottleneck.
17

Few-Shot & Zero-Shot Learning

26 min
What you'll learn
  • Learn from few examples
  • Use pre-trained models
  • Generalize to unseen classes

Few-shot learning classifies with just a handful of examples; zero-shot with none (using a class description instead). This leverages pre-trained models that already understand the world — instead of retraining, you adapt with a few examples or a prompt. The workflow: take a foundation model, provide k examples (few-shot) or a description (zero-shot), and it generalizes instantly.

fewshot.py
from transformers import pipeline
classifier = pipeline('zero-shot-classification')
result = classifier(
    'I bought a new phone',
    candidate_labels=['electronics', 'food', 'travel']
)
print(result['labels'][0])
Live Preview
Few-Shot & Zero-Shot Learning
0
Zero-shot
5
Few-shot
✓ Best Practice: Zero-shot means no training at all — just a pre-trained model and candidate labels. It's remarkable and increasingly common.
Try it yourself

What's the difference between few-shot and zero-shot?

Examples count.
Few-shot uses a few labeled examples; zero-shot uses none (only descriptions).
18

Active Learning

24 min
What you'll learn
  • Label the most valuable data
  • Reduce labeling cost
  • Use uncertainty sampling

Active learning flips the labeling problem: instead of labeling everything, the model picks the MOST INFORMATIVE examples for humans to label. Uncertainty sampling asks for labels on examples the model is least sure about. This can reduce labeling cost 10x with minimal accuracy loss — critical when labels are expensive (medical images, legal documents, expert annotation).

active.py
def uncertainty_sampling(model, unlabeled_pool, n=100):
    probs = model.predict_proba(unlabeled_pool)
    uncertainty = 1 - probs.max(axis=1)  # most uncertain = lowest max prob
    idx = np.argsort(uncertainty)[-n:]
    return idx
Live Preview
Active Learning
Model
Uncertain?
Label these
💡 Tip: Label the examples your model is confused about — not random ones. That's where the learning signal is.
Try it yourself

Why does active learning help?

Label cost.
It reduces labeling cost by focusing on the most informative examples.
19

Continual & Lifelong Learning

26 min
What you'll learn
  • Learn without forgetting
  • Handle new classes over time
  • Manage catastrophic forgetting

Real models face new classes and data distributions over their lifetime. Continual learning updates models without catastrophically forgetting old knowledge — the classic problem: retraining a network on new classes often destroys old ones. Solutions: replay buffers (keep examples), elastic weight consolidation (protect important weights), and parameter isolation. Essential for deployed models that keep learning.

continual.py
# Elastic Weight Consolidation idea
# Protect weights that mattered for old tasks
loss = new_task_loss + lambda_ * sum(F_i * (theta - theta_old)**2)
Live Preview
Continual & Lifelong Learning
Task A ✓
Task B ✓
Both ✓
🔎 Important: Catastrophic forgetting is real — a model trained on new classes can forget old ones entirely.
Try it yourself

What is catastrophic forgetting?

Forget old.
When a model forgets previously learned tasks after training on new ones.
20

Causal ML

28 min
What you'll learn
  • Distinguish correlation from causation
  • Estimate treatment effects
  • Use uplift modeling

Most ML predicts outcomes; causal ML estimates WHAT HAPPENS IF we intervene — the effect of a treatment, an ad, a drug. Correlation is not causation: ice cream sales and drownings correlate (summer), but neither causes the other. Causal methods (propensity scores, double ML, uplift modeling) estimate individual treatment effects — who responds to an intervention. This is decision-making ML, used in marketing, medicine, and policy.

causal.py
from econml.dml import CATE
model = CATE(model_y=reg, model_t=clf)
model.fit(Y, T, X)
# T=treatment, Y=outcome, X=features
effect = model.effect(X)
Live Preview
Causal ML
+12%
Treatment effect
-3%
No effect
⚠️ Common Mistake: Correlation ≠ causation. If you need to answer 'what happens if we change X', you need causal ML, not prediction.
Try it yourself

Uplift modeling answers which question?

Who responds.
Who will respond to the intervention — not just who will convert.
21

Text Embeddings at Scale

26 min
What you'll learn
  • Generate sentence embeddings
  • Use SBERT for semantic search
  • Build retrieval systems

Sentence embeddings map whole sentences/paragraphs to vectors for semantic search, clustering, and similarity. SBERT (Sentence-BERT) fine-tunes BERT so similar sentences get close vectors — enabling fast cosine-similarity search over millions of documents. This powers modern retrieval-augmented systems and recommendation. The ML angle: embeddings turn text into features any downstream model can use.

embedding.py
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('all-MiniLM-L6-v2')
embeddings = model.encode(['How to train a model', 'Cooking pasta'])
similarity = cosine_similarity([embeddings[0]], [embeddings[1]])
Live Preview
Text Embeddings at Scale
"hello"
[0.2, 0.8, ...]
✓ Best Practice: Semantic search via embeddings beats keyword search — it matches MEANING, not exact words.
Try it yourself

What does cosine similarity measure?

Angle.
How similar two vectors are, based on their angle.
22

Text Generation Fine-tuning

28 min
What you'll learn
  • Fine-tune LLMs for your domain
  • Use LoRA/QLoRA efficiently
  • Generate domain-specific text

Fine-tuning an LLM adapts it to your domain — support tickets, legal docs, product copy. LoRA (Low-Rank Adaptation) fine-tunes only a tiny fraction of parameters, making it feasible on consumer GPUs. QLoRA adds 4-bit quantization, cutting memory further. The result: an LLM that speaks your domain's language, cheaply fine-tuned on modest hardware.

lora.py
from peft import LoraConfig, get_peft_model
config = LoraConfig(r=8, lora_alpha=32, target_modules=['q_proj','v_proj'])
model = get_peft_model(base_model, config)
model = prepare_model_for_kbit_training(model)
Live Preview
Text Generation Fine-tuning
Full fine-tune
LoRA
✓ Best Practice: LoRA fine-tunes 1% of parameters with most of the performance — the standard way to adapt LLMs on a budget.
Try it yourself

What does LoRA stand for and why use it?

Low rank.
Low-Rank Adaptation — efficient fine-tuning of large models.
23

Retrieval-Augmented Generation (RAG)

30 min
What you'll learn
  • Combine retrieval with generation
  • Ground LLMs in your data
  • Build question-answering over documents

RAG is the production pattern for LLMs: retrieve relevant documents (embeddings + vector search), feed them to the LLM as context, and generate a grounded answer. This gives the LLM access to your private knowledge without retraining, dramatically reduces hallucination, and keeps answers up-to-date. The pipeline: embed docs → index in a vector DB → retrieve at query time → generate with context.

rag.py
# RAG pipeline
query_embedding = embed(query)
docs = vector_db.search(query_embedding, top_k=5)
context = '\n'.join(docs)
answer = llm.generate(f'Context: {context}\nQuestion: {query}')
Live Preview
Retrieval-Augmented Generation (RAG)
Query
Retrieve
Generate
🔎 Important: RAG is THE pattern for enterprise LLM apps — it grounds answers in your data and cuts hallucination.
Try it yourself

What problem does RAG solve?

Hallucination.
It grounds LLM answers in retrieved documents, reducing hallucination and enabling private data.
24

Vector Databases

26 min
What you'll learn
  • Store and search embeddings
  • Use FAISS/Pinecone/Chroma
  • Build semantic search

Vector databases index embeddings for fast similarity search — the backend of semantic search, RAG, and recommendation. Instead of exact keyword matches, they find the k nearest vectors (approximate nearest neighbor search). FAISS is Facebook's library (open-source, in-memory); Pinecone and Chroma are managed/embedded options. This is the storage layer for modern embedding-based ML.

vectordb.py
import faiss
import numpy as np

dimension = 384
index = faiss.IndexFlatL2(dimension)
index.add(embeddings)  # store vectors
D, I = index.search(query_vector, k=5)  # top 5 nearest
Live Preview
Vector Databases
Embed
Index
Search
💡 Tip: FAISS in-memory is great for prototyping; managed vector DBs (Pinecone) handle scale and persistence.
Try it yourself

What does a vector DB store?

Embeddings.
Vector embeddings, indexed for fast similarity search.
25

Sentiment & Emotion Analysis Deep Dive

24 min
What you'll learn
  • Go beyond positive/negative
  • Detect fine-grained emotion
  • Handle aspect-based sentiment

Basic sentiment is positive/negative; advanced analysis goes further — fine-grained emotions (joy, anger, fear), aspect-based sentiment ('battery is bad, camera is great'), and intensity. Aspect-based analysis extracts which specific feature a sentiment targets, powering product feedback mining. The ML angle: this is fine-tuned classification + span extraction, and domain matters enormously.

sentiment.py
from transformers import pipeline
sent = pipeline('sentiment-analysis')
aspect = pipeline('token-classification', model='aspect-model')
results = sent('The battery is awful but the screen is great!')
Live Preview
Sentiment & Emotion Analysis Deep Dive
😀 92%
Positive
😞 8%
Negative
💡 Tip: Aspect-based sentiment reveals WHAT people love/hate about your product — far more actionable than overall polarity.
Try it yourself

What is aspect-based sentiment?

Feature-level.
Sentiment about specific aspects/features, not just the whole text.
26

Named Entity Recognition at Scale

24 min
What you'll learn
  • Extract entities from text
  • Build custom entity extractors
  • Apply to information pipelines

NER extracts structured entities — people, organizations, dates, amounts — from unstructured text, turning documents into structured records. Custom NER trains on your domain's entity types (drug names, product SKUs, legal citations). At scale, NER feeds knowledge graphs and databases. It's the bridge from text to structured data, powering search, compliance, and analytics.

ner.py
from transformers import AutoModelForTokenClassification
model = AutoModelForTokenClassification.from_pretrained('ner-model', num_labels=7)
entities = model.predict(text)  # returns PER, ORG, LOC, DATE, etc.
Live Preview
Named Entity Recognition at Scale
Sufyan: PER Google: ORG Lahore: LOC
🔎 Important: Fine-tuning NER on your domain's entity types turns documents into structured databases automatically.
Try it yourself

Name one application of NER at scale.

Extract facts.
Extracting entities from legal documents, medical records, or news for search/analytics.
27

Machine Translation Systems

24 min
What you'll learn
  • Build translation pipelines
  • Use seq2seq transformers
  • Evaluate with BLEU

Translation maps text between languages using encoder-decoder transformers. Production systems evaluate with BLEU (n-gram overlap), handle dozens of languages, and often use a pivot language. The ML angle: translation is the canonical sequence-to-sequence task — what you learn here transfers to summarization, paraphrasing, and dialogue.

translate.py
from transformers import pipeline
translator = pipeline('translation', model='facebook/nllb-200-distilled-600M')
result = translator('Hello world', src_lang='eng_Latn', tgt_lang='urd_Arab')
Live Preview
Machine Translation Systems
Hello
ہیلو
💡 Tip: NLLB supports 200 languages — one model for nearly any translation need.
Try it yourself

What does BLEU measure?

Overlap.
N-gram overlap between machine translation and reference translations.
28

Speech-to-Text Pipelines

26 min
What you'll learn
  • Transcribe audio with Whisper
  • Handle multiple languages
  • Build voice interfaces

ASR converts audio to text — the frontend of voice assistants, meeting transcription, and accessibility. Whisper processes audio spectrograms with a transformer, handling noise and multiple languages robustly. The ML angle: audio is preprocessed (resampled to 16kHz), turned into log-mel spectrograms, then fed to a seq2seq model that outputs text tokens.

asr.py
from transformers import pipeline
asr = pipeline('automatic-speech-recognition', model='openai/whisper-small')
result = asr('meeting.mp3')
print(result['text'])
Live Preview
Speech-to-Text Pipelines
💡 Tip: Whisper expects 16kHz audio — resample first or it silently transcribes garbage.
Try it yourself

What preprocessing does audio need before ASR?

Sample rate.
Resample to 16kHz and convert to log-mel spectrogram.
29

Model Deployment Patterns

28 min
What you'll learn
  • Serve models as APIs
  • Choose batch vs real-time
  • Design serving architecture

A trained model becomes a product only when deployed. Real-time serving: an API endpoint returning predictions in milliseconds (FastAPI + model in memory). Batch: process large datasets offline. The architecture: load model once, preprocess input, predict, post-process output, return JSON. Deployment is where ML meets software engineering — latency, throughput, and reliability become first-class concerns.

deploy.py
from fastapi import FastAPI
import joblib
app = FastAPI()
model = joblib.load('model.joblib')
@app.post('/predict')
def predict(features: list):
    pred = model.predict([features])
    return {'prediction': pred.tolist()}
Live Preview
Model Deployment Patterns
Model
API
Cloud
✓ Best Practice: Load the model ONCE at startup, not per-request — repeated loading kills latency.
Try it yourself

Real-time vs batch serving — which for fraud detection?

Latency.
Real-time — fraud detection needs instant decisions.
30

Docker for ML

26 min
What you'll learn
  • Containerize ML models
  • Create reproducible environments
  • Deploy consistently

Docker packages your model + dependencies + code into one portable container that runs anywhere — your laptop, a cloud VM, a Kubernetes cluster. This solves 'it works on my machine'. The Dockerfile: pull a Python image, install requirements, copy the model and app, expose the port. Containers are the universal deployment unit in production ML.

dockerfile
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ['uvicorn', 'app:app', '--host', '0.0.0.0', '--port', '8000']
Live Preview
Docker for ML
🐳 Container
✓ Best Practice: If your model can't be containerized, it can't be reliably deployed. Docker is non-negotiable in production ML.
Try it yourself

What problem does Docker solve?

Environment.
Reproducible, portable environments — 'works on my machine' disappears.
31

Model Monitoring & Drift

28 min
What you'll learn
  • Monitor production ML
  • Detect data and concept drift
  • Alert on model decay

Deployed models decay — data distributions shift (data drift), or relationships change (concept drift). Monitoring tracks input distributions, prediction distributions, and business metrics over time, alerting when they diverge from training baselines. Tools: Evidently, WhyLabs, custom dashboards. A model that isn't monitored is a model silently failing in production.

monitor.py
from evidently.report import Report
from evidently.metric_preset import DataDriftPreset
report = Report(metrics=[DataDriftPreset()])
report.run(reference_data=training_df, current_data=live_df)
report.save_html('drift_report.html')
Live Preview
Model Monitoring & Drift
Drift: age
Drift: income
🔎 Important: Data drift is silent model decay — the model still 'runs' but its predictions slowly become wrong.
Try it yourself

What is the difference between data and concept drift?

Input vs relationship.
Data drift = input distribution changes; concept drift = the input-output relationship changes.
32

Experiment Tracking with MLflow

26 min
What you'll learn
  • Track every experiment
  • Reproduce results
  • Version models and data

Experiment tracking records parameters, metrics, code versions, and model artifacts for every training run — so you can compare, reproduce, and audit. MLflow is the standard: log params/metrics, save models to a registry, compare runs in a UI. Without tracking, you'll forget which config produced that great result. This is the foundation of ML engineering discipline.

mlflow.py
import mlflow
mlflow.set_experiment('churn-prediction')
with mlflow.start_run():
    mlflow.log_params({'lr': 0.01, 'n_estimators': 100})
    mlflow.log_metric('accuracy', 0.93)
    mlflow.sklearn.log_model(model, 'model')
Live Preview
Experiment Tracking with MLflow
0.93
Accuracy
42
Runs
✓ Best Practice: If you can't reproduce your best result, it didn't happen. Track everything, always.
Try it yourself

Why track ML experiments?

Reproduce.
To compare, reproduce, and audit which configuration produced which result.
33

Feature Stores

26 min
What you'll learn
  • Centralize features
  • Ensure train/serve consistency
  • Share features across teams

A feature store is a central repository for ML features — computed once, reused across models, served consistently in training and inference. The critical problem it solves: train/serve skew, where features are computed differently in training vs production, silently degrading models. Feature stores (Feast, Tecton) version features, enable reuse, and guarantee consistency.

feature_store.py
# Feast feature store
feature_store = FeatureStore(repo_path='./feature_repo')
features = feature_store.get_online_features(
    features=['user:age', 'user:total_spend'],
    entity_rows=[{'user_id': 123}]
)
Live Preview
Feature Stores
Features
Store
Serve
🔎 Important: Train/serve skew is a top silent killer — feature stores eliminate it by making feature computation identical in both.
Try it yourself

What is train/serve skew?

Inconsistency.
When features are computed differently in training vs serving, degrading predictions.
34

Model Compression & Distillation

26 min
What you'll learn
  • Shrink models for deployment
  • Use distillation and quantization
  • Speed up inference

Production models must be fast and small. Quantization reduces precision (float32→int8, ~4x smaller). Pruning removes unimportant weights. Distillation trains a small 'student' to mimic a large 'teacher's' outputs — often retaining most accuracy at a fraction of size. For neural nets, distillation is the most effective: the student learns the teacher's soft probabilities, capturing more than hard labels.

compress.py
import torch
model_fp32 = model
model_int8 = torch.quantization.quantize_dynamic(
    model_fp32, {torch.nn.Linear}, dtype=torch.qint8
)
Live Preview
Model Compression & Distillation
50MB
12MB
💡 Tip: Distillation usually beats quantization for accuracy — the student learns richer soft targets than just labels.
Try it yourself

Why compress ML models?

Deploy cost.
Faster inference, lower latency, cheaper serving, and edge deployment.
35

Explainable ML in Production

26 min
What you'll learn
  • Explain every prediction
  • Use SHAP for attribution
  • Satisfy compliance needs

Production ML in regulated domains — finance, healthcare, hiring — requires explaining individual predictions. SHAP computes per-feature attribution (which features pushed this decision up/down). It satisfies 'right to explanation' laws, helps debug, and builds user trust. Explainability isn't optional in production; it's often the difference between deploying and not deploying.

explain.py
import shap
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X)
shap.initjs()
shap.force_plot(explainer.expected_value, shap_values[0], X.iloc[0])
Live Preview
Explainable ML in Production
age
income
✓ Best Practice: Explainability is a feature, not an afterthought — users and regulators demand it.
Try it yourself

What does SHAP provide?

Attribution.
Per-feature contribution to each individual prediction.
36

Canary & Shadow Deployment

24 min
What you'll learn
  • Roll out models safely
  • Compare old vs new
  • Minimize deployment risk

Rolling out a new model is risky. Shadow mode runs the new model alongside the old, logging both but serving the old — you compare performance without user impact. Canary deployment routes a small percentage of traffic (5%) to the new model, ramping up if metrics hold. These patterns let you de-risk model changes, catching failures before they affect all users.

canary.py
# Canary deployment
traffic_split = {'old_model': 0.95, 'new_model': 0.05}
# Monitor error rate and business metrics
# If new model holds, ramp: 0.90/0.10 → 0.50/0.50 → 0/1.0
Live Preview
Canary & Shadow Deployment
95% old
5% new
💡 Tip: Never flip a model switch all at once — canary and shadow deployments are the professional way to change models.
Try it yourself

What's the difference between shadow and canary?

Traffic served.
Shadow: new model sees traffic but doesn't serve. Canary: new model serves a small traffic fraction.
37

Edge ML

26 min
What you'll learn
  • Deploy models on devices
  • Optimize for edge constraints
  • Use edge-specific frameworks

Edge ML runs models on phones, cameras, sensors — offline, private, low-latency. Constraints: memory, battery, compute. Solutions: model compression (quantization/pruning/distillation), edge frameworks (TensorFlow Lite, ONNX Runtime, Core ML), and specialized hardware (NPUs). Applications: face unlock, voice assistants, smart cameras. Privacy is the killer app — data never leaves the device.

edge.py
import onnxruntime as ort
session = ort.InferenceSession('model_quantized.onnx')
inputs = {'input': input_array}
output = session.run(None, inputs)
Live Preview
Edge ML
📱
int8
🔎 Important: Edge ML is the fastest-growing deployment target — privacy and latency drive everything offline.
Try it yourself

Why deploy ML on edge devices?

Privacy/latency.
Privacy (data stays on device), low latency, and offline capability.
38

Adversarial ML & Security

28 min
What you'll learn
  • Understand adversarial attacks
  • Harden models against attacks
  • Build secure ML systems

ML models can be fooled — tiny perturbations to an image that are invisible to humans can flip a classifier's decision. Adversarial attacks also include data poisoning (corrupt training data) and model extraction (stealing models). Defenses: adversarial training, input sanitization, model monitoring. As ML handles security-critical decisions, robustness against attack becomes essential, not optional.

adversarial.py
# Adversarial attack: add imperceptible noise
import torch
epsilon = 0.01
perturbation = epsilon * torch.sign(gradient)
adversarial_input = original_input + perturbation
Live Preview
Adversarial ML & Security
Clean ✓
Perturbed ✗
⚠️ Common Mistake: Your model can be fooled by changes invisible to humans — security-critical ML must be hardened.
Try it yourself

What is an adversarial example?

Fool model.
An input with tiny perturbations that changes the model's prediction.
39

ML at Scale: Distributed Training

28 min
What you'll learn
  • Train on multiple GPUs
  • Use data and model parallelism
  • Scale to massive datasets

Modern models and datasets don't fit one machine. Distributed training splits work: data parallelism (same model, different data chunks per GPU, synchronize gradients) and model parallelism (different layers on different GPUs). Frameworks: PyTorch DistributedDataParallel, Horovod, Ray. This is how GPT-4-scale models are trained — thousands of GPUs working in concert.

distributed.py
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel

dist.init_process_group('nccl')
model = DistributedDataParallel(model)
# Each GPU trains on its data shard, gradients sync each step
Live Preview
ML at Scale: Distributed Training
GPU₁
GPU₂
GPU₃
🔎 Important: Distributed training is how frontier models are made — understand the data-parallel pattern and the rest follows.
Try it yourself

What's data parallelism?

Split data.
Same model replicated, each GPU trains on a data shard, gradients synchronized.
40

Capstone: Production ML System

70 min
What you'll learn
  • Build an end-to-end ML system
  • Apply MLOps best practices
  • Ship a deployed, monitored model

Your final capstone: build a complete production ML system. Pick a problem, train a model with MLflow tracking, version it, containerize with Docker, serve behind FastAPI, set up monitoring for drift, and document the whole pipeline. This integrates everything from the course — the deliverable is a deployed system, not a notebook. It's the portfolio piece that proves you're a production ML engineer.

capstone.py
# Production ML stack
# 1. Train (MLflow-tracked)
# 2. Package (Docker)
# 3. Serve (FastAPI)
# 4. Monitor (Evidently)
# 5. Deploy (cloud/K8s)
print('End-to-end production ML system')
Live Preview
Capstone: Production ML System
Train
Deploy
Monitor
✓ Best Practice: A deployed, monitored model is worth 100 notebooks — this capstone is your proof you can ship ML.
Try it yourself

What separates a production ML system from a notebook?

Deploy + monitor.
It's deployed, containerized, monitored for drift, and reproducible.
You've completed all 40 advanced lessons. You're now an ML engineer.

Practice your skills or return to the ML hub.

📱 Scan this QR code with your phone camera to instantly open this page.

Works on iOS, Android, and any modern device. No app installation required.

Account Verified!

Your email has been verified successfully.