Classical MLbeginnermust-know4 min

Bias–Variance Tradeoff

How to fix a model that makes bad predictions using simple error tuning.

When a machine learning model makes mistakes, the errors come from three main sources. First, bias happens when a model is too simple and misses the real pattern completely. Second, variance happens when a model is too complex and memorizes random noise instead of learning general patterns. Third, irreducible noise comes from unavoidable random mistakes in the data itself. Finding the right balance means tweaking model size until predictions are accurate on new data.

Classical MLbeginnermust-know3 min

Overfitting vs Underfitting

Everyone can define it. Fewer can diagnose it from a learning curve.

Overfitting is learning the training set's noise as if it were signal — training error keeps dropping while validation error rises. Underfitting is failing to learn the signal at all — both errors stay high and close together. Detect it by tracking both curves as a function of training set size and epochs. Fix overfitting with more data, regularization, augmentation and early stopping; fix underfitting with capacity, features and longer training.

Classical MLbeginnermust-know4 min

Linear Regression

Simple on paper, brutal in interviews. Most candidates stumble on the assumptions.

Linear Regression models continuous targets as y = Xβ + ε. Ordinary Least Squares (OLS) minimizes squared residuals, yielding the closed-form solution β = (XᵀX)⁻¹Xᵀy. Under the Gauss-Markov assumptions, OLS is the Best Linear Unbiased Estimator (BLUE). Key interview topics include closed-form derivation, assumption validation, multicollinearity, and OLS vs Gradient Descent trade-offs.

Classical MLbeginnermust-know4 min

Logistic Regression

The baseline classifier every ML candidate is expected to derive on a whiteboard.

Logistic regression predicts the probability that something belongs to a class, like whether an email is spam. It adds up the features with weights, just like linear regression, then squashes the result through an S-shaped curve so the output always lands between 0 and 1. It is trained with log loss, which punishes confident wrong answers heavily. The weights are easy to read, since each one says how much a feature raises or lowers the odds. Despite its name, it is used for classification.

Classical MLbeginnermust-know5 min

Cross-Validation Done Right

Why one train-test split is luck, and how k-fold fixes it.

Cross Validation evaluates how a machine learning model generalizes to unseen test data by partitioning training datasets into multiple validation splits. Standard K-Fold splits data into K equal folds. Stratified K-Fold preserves class label proportions across folds, essential for imbalanced classification. Group K-Fold prevents data leakage by ensuring all samples from a specific subject or user stay in the same fold. Time Series Split respects temporal causality, using past data to predict future time steps.

Deep Learningbeginnermust-know4 min

Activation Functions

Without them, a deep network is just one big straight line.

Activation functions introduce non linearity into neural networks, allowing them to learn complex non linear patterns. Without non linear activation steps, a multi layer neural network collapses into a simple linear model regardless of depth. Common activations include Sigmoid for probabilities between 0 and 1, Tanh for zero centered signals between minus 1 and plus 1, ReLU for fast computation, and GELU for modern transformer architectures.

Deep Learningbeginnermust-know4 min

Dropout

Randomly switching off neurons, which somehow makes the network better.

Dropout fights overfitting by randomly switching off a fraction of neurons at each training step, often half in large layers. Because any neuron might vanish, the network cannot rely on fragile partnerships between specific neurons, so it learns more robust, spread-out features. In effect it trains a huge number of smaller sub-networks that share weights. At prediction time nothing is switched off, and the outputs are rescaled so the overall signal stays the same size as during training.

Metrics & Evaluationbeginnermust-know4 min

Precision, Recall & F1

Catch every real case, or avoid false alarms? You rarely get both.

Precision measures how often your model is right when it flags something as positive. Recall measures how many of the actual positive cases your model managed to find. Raising precision usually lowers recall and vice versa. Choosing which metric matters most comes down to understanding which type of mistake causes more real world harm.

Metrics & Evaluationbeginnermust-know4 min

Why Accuracy Lies

Why 99 percent accuracy can trick you into keeping a completely useless machine learning model.

The accuracy trap happens when you use simple accuracy to judge a model on unbalanced datasets. In a rare disease dataset where 99 percent of people are healthy, a simple guessing model that predicts healthy for everyone achieves 99 percent accuracy while missing every single sick person. Solving this problem requires switching to metrics like precision, recall, and cost matrices.

Data & Feature Engineeringbeginnermust-know4 min

Feature Engineering Fundamentals

Better data beats fancy algorithms. Where 80% of real-world model accuracy improvements actually come from.

Feature engineering extracts predictive signals from raw data. Techniques must match the target model family: tree-based models need minimal scaling but benefit from target stats and ratios; linear/neural models require strict feature scaling, one-hot encoding, and non-linear log or cyclical transforms (sin/cos). Key topics include handling missingness, high-cardinality encodings, interaction features, and preventing target leakage.

Responsible AI & Behaviouralbeginnermust-know5 min

Telling Your ML Project Story

Telling the story of your best ML project so it actually lands.

Telling Your ML Project Story covers behavioral interview techniques for machine learning engineers. Interviewers use project walkthrough questions to evaluate technical depth, system design intuition, business impact, and problem solving under constraints. Structuring responses using the Situation, Task, Action, and Result (STAR) framework ensures clear, compelling communication of technical achievements.

Classical MLintermediatemust-know5 min

L1 vs L2 Regularization

Two penalties that stop overfitting, and only one of them deletes features.

Both stop a model from overfitting by adding a penalty for large weights to the loss. L1, also called Lasso, penalises the sum of the absolute weights. That pushes unhelpful weights all the way to zero, so it quietly removes useless features for you. L2, also called Ridge, penalises the sum of the squared weights. That shrinks every weight smoothly but almost never to zero, and it copes better when features are closely related. Use L1 to pick features, and L2 to calm everything down.

Classical MLintermediatemust-know4 min

Gradient Descent & Its Variants

Whole dataset, one example, or a small batch per step, and why batches won.

Gradient descent trains a model by repeatedly nudging its weights downhill on the loss. The variants differ in how much data they look at per nudge. Batch gradient descent uses the whole dataset each time, which is accurate but slow. Stochastic gradient descent uses a single example each time, which is fast but jumpy. Mini-batch, using around 32 to 256 examples per step, is what everyone actually uses. It fits GPUs well, and its slight noise even helps the model escape poor spots.

Classical MLintermediatemust-know5 min

Bagging vs Boosting

Bagging fixes a model that is too complex. Boosting fixes one that is too simple.

Bagging and Boosting are the two dominant ensemble learning paradigms in machine learning. Bagging (Bootstrap Aggregating) trains independent complex base models in parallel on random data subsets to reduce variance (Random Forest). Boosting trains simple weak base models sequentially, focusing each new model on errors made by previous models to reduce bias (AdaBoost, XGBoost).

Classical MLintermediatemust-know5 min

Principal Component Analysis

Fewer features, most of the information kept. The classic way to shrink data.

PCA reduces the number of features while keeping as much information as possible. It finds the directions along which your data varies the most, and rotates the data to line up with them. The first direction captures the most spread, the second the next most, and so on, each at right angles to the rest. Keep the top few and drop the others, and you have fewer features that still describe the data well. Always scale your features first, or the largest-unit feature dominates.

Classical MLintermediatemust-know5 min

Handling Imbalanced Datasets

When 99 percent of your data is one class, accuracy stops meaning anything.

Class Imbalance occurs when majority classes dominate minority target classes (e.g. 99.9% non-fraud vs 0.1% fraud). Standard models achieve 99.9% dummy accuracy by predicting majority class everywhere while completely missing minority events. Solutions include Resampling (Random Undersampling, SMOTE oversampling), Cost Sensitive Learning (class weighting, Focal Loss), and evaluating via PR-AUC and F1-Score rather than raw Accuracy.

Deep Learningintermediatemust-know5 min

Backpropagation

The engine of deep learning. Most candidates know the intuition; few can trace matrix dimensions correctly.

Backpropagation computes gradients of scalar loss L with respect to all network weights W using the multivariable chain rule in reverse mode. Running backwards from output to input computes all ∂L/∂W in O(W) operations, whereas finite differences or forward-mode differentiation require O(W²) complexity. Key interview topics include computational graphs, local gradients, error signals (δ), and matrix shape matching.

Deep Learningintermediatemust-know4 min

Vanishing & Exploding Gradients

Why deep networks used to stop learning, or blow up, partway through training.

Vanishing and Exploding Gradients are major training instabilities in deep neural networks and recurrent models. The chain rule multiplies local derivatives across layers during backpropagation. If local derivatives are smaller than 1, multiplying them repeatedly causes gradients to shrink exponentially toward zero, preventing early layers from learning. If local derivatives are larger than 1, gradients grow exponentially, causing weight instability or NaN overflow.

Deep Learningintermediatemust-know5 min

Batch Normalization

Keeping the numbers inside a network steady so it trains faster.

Batch normalisation keeps the numbers flowing through a network in a steady range. For each feature, it takes the current mini-batch, shifts the values to an average of zero and a spread of one, then lets the network learn its own preferred scale and shift on top. This makes training faster and more stable, allows higher learning rates, and adds a mild regularising effect. It depends on batch statistics, so it struggles with tiny batches, which is why Transformers use layer normalisation instead.

Deep Learningintermediatemust-know5 min

SGD, Momentum, Adam & AdamW

From plain gradient descent to Adam: how networks decide each weight update.

Optimisers decide how to update a network's weights from the gradient. Plain stochastic gradient descent steps straight downhill. Momentum adds a running average of past steps, so updates build speed in consistent directions and roll past small bumps. Adam goes further and gives every weight its own step size, based on how large and how noisy its recent gradients have been, so it works well with little tuning. AdamW fixes how Adam applies weight decay, and is now the default for training Transformers.

Deep Learningintermediatemust-know4 min

Transfer Learning & Fine-Tuning

Start from a model that already learned a lot, then adapt it to your task.

Transfer Learning adapts a model pretrained on a large source dataset (ImageNet, C4, Wikipedia) to a specific target task. Strategies range from Feature Extraction (freezing backbone weights and training a new linear classification head) to Full Fine-Tuning and Parameter-Efficient Fine-Tuning (PEFT / LoRA). Key decision factors include target dataset size and domain similarity to the source data.

Deep Learningintermediatemust-know5 min

Debugging a Training Run

A checklist for when your loss spikes, stalls or does something strange.

Debugging a Training Run requires a structured diagnostic protocol to isolate bugs in data pipelines, loss functions, and model architectures. Key steps include overfitting a single batch of 10 samples to zero loss, verifying loss values at step zero, monitoring gradient norms, checking for NaN/Inf floats, and inspecting activation statistics. Systematic debugging prevents wasted GPU compute costs and resolves training stalls quickly.

NLP & Transformersintermediatemust-know5 min

The Attention Mechanism

How a model knows which earlier words matter for the one it is reading.

When you read "The cat sat on the mat because it was tired", you know "it" means the cat, because you looked back at the right word. Attention lets a model do the same. For each word, it scores how relevant every other word is, then builds that word's meaning mostly from the high scorers. Older models squeezed a whole sentence into one fixed summary and lost detail on long inputs. It is the core idea inside every Transformer, including ChatGPT.

NLP & Transformersintermediatemust-know5 min

Transformer Architecture

The design behind ChatGPT and almost every modern language model.

The Transformer is the design behind almost every modern language model. Older models read text one word at a time, which was slow and tended to forget early words. A Transformer looks at all the words at once and uses attention to let each word pull in information from the others, so GPUs can process a whole passage in parallel. It is built from repeated blocks of attention followed by a small feed-forward network, with shortcut connections and normalisation keeping deep stacks trainable.

NLP & Transformersintermediatemust-know5 min

Tokenization & BPE

How text gets chopped into the pieces a model actually reads.

Tokenization breaks raw text strings into numerical token IDs that neural networks can process. Character level tokenization creates tiny vocabularies but long sequences. Word level tokenization creates huge vocabularies with frequent out of vocabulary errors. Byte Pair Encoding (BPE) is a subword tokenization algorithm that iteratively merges the most frequent pairs of adjacent bytes or characters. BPE balances vocabulary size and sequence length, handling rare words and code efficiently without out of vocabulary errors.

NLP & Transformersintermediatemust-know5 min

BERT vs GPT: Encoder vs Decoder

Two kinds of Transformer: one built to understand text, one built to write it.

BERT and GPT are both Transformers, built for different jobs. BERT reads a whole sentence at once, looking both left and right, and is trained by filling in hidden words. That makes it strong at understanding text: classifying it, searching it, or finding answers inside it. GPT reads strictly left to right and is trained to predict the next word, which makes it strong at writing new text. Most chatbots today are GPT-style, while search systems often still use BERT-style models.

LLMs & GenAIintermediatemust-know5 min

Pretraining → SFT → RLHF

The three stages that turn a pile of internet text into a helpful assistant.

Building modern production Large Language Models involves three sequential training stages: Pretraining, Supervised Fine Tuning (SFT), and Reinforcement Learning from Human Feedback (RLHF / DPO). Pretraining consumes trillions of web text tokens via next token prediction to build raw world knowledge. SFT fine-tunes base models on high quality instruction prompt-response pairs to learn conversational formatting. RLHF / DPO aligns models with human preferences for helpfulness, honesty, and safety.

LLMs & GenAIintermediatemust-know5 min

Fine-Tune vs RAG vs Prompt: Choosing

The most common GenAI design question: prompt it, give it documents, or train it?

Choosing between Prompt Engineering, RAG, and Fine Tuning depends on task requirements. Prompt Engineering adapts baseline LLM behavior quickly using zero shot instructions. Retrieval Augmented Generation (RAG) injects dynamic, up to date external knowledge into context to prevent hallucinations and cite sources. Fine Tuning modifies model weights to internalize specific formatting, style, tone, or specialized domain syntax.

LLMs & GenAIintermediatemust-know5 min

Retrieval-Augmented Generation

How to let a model answer from your documents instead of its memory.

A language model only knows what was in its training data, and it cannot see your company's documents. RAG fixes that. When a question comes in, the system first searches a store of your documents for the most relevant passages, then pastes those passages into the prompt alongside the question. The model answers from that text instead of from memory. This keeps answers current, lets the system cite its sources, and greatly reduces made-up answers, all without retraining the model.

LLMs & GenAIintermediatemust-know5 min

Why LLMs Hallucinate

Why language models state false things with total confidence.

Hallucination is when a language model states something false with full confidence. It happens because the model is trained to predict the most likely next word, not the true one, and nothing in that training rewards saying "I don't know". Gaps or errors in its training data make it worse. A wrong answer and a right one can look identical from the outside. The main fixes are giving the model real source text to answer from, asking it to cite that text, and checking claims against trusted sources.

Reinforcement Learningintermediatemust-know5 min

Value-Based vs Policy-Based Methods

Learn how good each action is, or learn what to do directly?

Reinforcement Learning algorithms divide into Value-Based methods (Q-Learning, DQN) and Policy-Based methods (REINFORCE, PPO). Value-based methods learn action-value function Q(s, a), deriving implicit greedy policies a = argmax_a Q(s, a). Policy-based methods parameterize policy π_θ(a|s) directly, optimizing parameters θ via gradient ascent on expected return. Actor-Critic methods combine both: an Actor policy π_θ(a|s) and a Critic value function V_ϕ(s).

Reinforcement Learningintermediatemust-know4 min

Multi-Armed Bandits

Choosing between slot machines, which is secretly how A/B tests and feeds work.

A Multi-Armed Bandit (MAB) is a simplified Reinforcement Learning framework where an agent chooses among K independent actions ("arms") to maximize cumulative reward. Unlike full MDPs, bandits have no state transitions—each action choice is stateless and independent. MABs replace traditional static A/B testing in digital marketing, ad click optimization, and website UI layout experiments by dynamically routing traffic to high-performing variations while continuously testing alternatives.

RecSys & Searchintermediatemust-know5 min

Collaborative Filtering

People like you liked this. The oldest idea in recommendations.

Collaborative Filtering (CF) recommends items to users by leveraging preference patterns from a crowd of similar users or items. User-Based CF finds users with similar interaction histories; Item-Based CF finds items co-liked by the same users. Matrix Factorization (SVD / ALS) decomposes the sparse User-Item interaction matrix R (N × M) into low-rank user matrices U (N × k) and item matrices V (M × k), predicting unobserved ratings as R_ui ≈ u_i · v_j.

RecSys & Searchintermediatemust-know4 min

The Cold Start Problem

How to recommend items or personalize feeds when zero interaction history exists for new users or items.

The Cold-Start Problem occurs in recommender systems when a new user joins (User Cold Start) or a new item is uploaded (Item Cold Start), resulting in zero historical interaction logs. Because Collaborative Filtering relies on interaction history, pure CF models fail. Production solutions include Content-Based embeddings (extracting text/image features via Multimodal models), Hybrid Architectures, Active Learning onboarding surveys, and Multi-Armed Bandit exploration algorithms (Epsilon-Greedy, Thompson Sampling).

ML System Designintermediatemust-know5 min

A Framework for Any ML Design Round

The 45-minute whiteboard round that determines your engineering level at tier-1 tech companies.

ML System Design interviews evaluate end-to-end architectural thinking. To succeed, use a structured 6-step framework: Clarify Problem & Business Metrics -> Data Ingestion & Features -> Baseline & Model Design -> Offline/Online Evaluation -> Serving & Latency Budget -> Monitoring & Feedback Loops. Always lead with simple heuristics before complex deep learning, and state tradeoffs out loud.

ML System Designintermediatemust-know5 min

Framing a Business Problem as ML

Turning a vague business goal into something a model can actually learn.

Problem Framing translates vague real world business objectives into concrete machine learning problems. Key steps include identifying the core prediction target, defining input features and output labels, selecting appropriate loss functions, and establishing metrics that align model performance directly with business KPIs. Proper framing prevents building models that optimize high accuracy while completely failing business goals.

ML System Designintermediatemust-know5 min

Online vs Offline Evaluation

Why a model with stellar offline AUC can fail completely when deployed to real production users.

Evaluating ML systems requires a two-stage process: Offline Evaluation on historical datasets (ROC-AUC, NDCG, RMSE) and Online Evaluation on live production traffic (A/B testing, CTR, Conversion Rate, Latency). A major challenge in applied ML is offline-online metric misalignment, caused by position bias, selection bias, feedback loops, and static offline data failing to capture dynamic user behavioral reactions.

ML System Designintermediatemust-know5 min

Batch vs Real-Time Inference

Predict on demand, or run everything overnight? It depends on freshness.

Batch vs Real-Time Inference represents the fundamental serving architecture choice in production ML systems. Batch inference precomputes predictions for all users or items offline (e.g. nightly Spark jobs) and stores results for fast lookup. Real-time inference computes predictions on demand when a request arrives, using the freshest features. Many production systems use a hybrid approach combining both.

ML System Designintermediatemust-know5 min

Training–Serving Skew

When a model performs great during offline training but fails in live production due to mismatched data or logic.

Training Serving Skew happens when the data or environment during live inference does not match what was used during model training. Common causes include calculating features differently in real time versus offline batch jobs, data leakage during training, or feature values changing between training and serving. Engineers prevent skew by using unified feature stores, shared feature transformation code, and point in time data logging.

ML System Designintermediatemust-know5 min

Communicating Tradeoffs Out Loud

Explaining your design choices out loud, which is half of the interview.

Communicating Tradeoffs Out Loud is a critical skill in machine learning system design interviews. Every technical design choice involves compromises between latency, accuracy, cost, memory, and operational complexity. Strong candidates state their architectural choices explicitly, explain why alternative approaches were rejected, and justify how their compromises serve business goals.

MLOps & Productionintermediatemust-know4 min

Data Drift vs Concept Drift

Why models that hit 99% accuracy in offline testing decay silently 3 months after deployment.

Data Drift (Covariate Shift) occurs when feature input distributions P(X) change over time while target rules P(Y|X) remain fixed. Concept Drift occurs when the relationship between features and target P(Y|X) changes. Detecting drift requires statistical tests like Population Stability Index (PSI), Kolmogorov-Smirnov (KS) test, and adversarial drift classifiers. Mitigations range from feature re-scaling to retraining schedules.

MLOps & Productionintermediatemust-know5 min

What to Monitor in Production

What to watch once a model is live, so you hear about failures first.

Model Monitoring tracks the health of deployed ML systems across four distinct layers: Software System Metrics (Latency, QPS, Memory), Input Data Drift (Feature distribution PSI/KS-tests), Prediction Drift (Output score distribution shifts), and Model Quality (Ground-truth performance). When true labels arrive with long delays (e.g. 30-day loan defaults), input and prediction drift act as early proxy indicators of performance degradation.

Metrics & Evaluationintermediatemust-know4 min

ROC-AUC vs PR-AUC

With 0.1% positives, ROC-AUC of 0.97 can mean a useless model.

ROC-AUC plots true positive rate against false positive rate across all thresholds and equals the probability the model ranks a random positive above a random negative. It is threshold-free and prevalence-independent — which is exactly its weakness. Because FPR's denominator is the huge negative class, thousands of false positives barely move it. PR-AUC uses precision, whose denominator is what you flagged, so it collapses honestly when the positive class is rare. Use PR-AUC for imbalanced problems.

Metrics & Evaluationintermediatemust-know4 min

Data Leakage

0.99 AUC in the notebook, 0.61 in production. Every time, it's leakage.

Leakage is any information in training that will not be available at prediction time. It comes in three flavours: target leakage (a feature is a consequence of the label), train–test contamination (preprocessing or duplicate rows cross the split), and temporal leakage (training on the future). The symptom is performance that looks too good and collapses in production. The defences are a strict per-fold pipeline, point-in-time correct feature joins, and asking of every feature "would I have known this then?"

Metrics & Evaluationintermediatemust-know4 min

Slice-Based & Subgroup Evaluation

A great overall score can hide a model failing badly for one group.

Slice-Based Evaluation (Subgroup Analysis) evaluates model performance independently across critical data subsets (e.g. device types, user cohorts, rare categories). A model with 95% global accuracy may suffer a catastrophic 40% failure rate on low-end Android phones or minority demographic slices. Best practices require defining key slices upfront, running automated slicing frameworks (DataSlice, SliceFinder), and enforcing minimum performance floors per slice.

Metrics & Evaluationintermediatemust-know5 min

Mapping Model Metrics to Business Metrics

Connecting your model's score to revenue, signups or retention.

Machine learning models optimize offline mathematical surrogate losses (Log Loss, MSE, Cross-Entropy), whereas businesses care about online KPIs (Revenue, Conversion Rate, Customer Acquisition Cost, User Retention). Aligning model metrics to business outcomes requires mapping offline error thresholds to dollar utility functions, calibrating output probabilities, and running controlled A/B experiment loops.

Data & Feature Engineeringintermediatemust-know5 min

SQL Questions in ML Interviews

The SQL patterns that keep coming up in ML engineering interviews.

SQL is the universal data querying language for building training datasets and feature stores. ML interview SQL questions evaluate your ability to compute sliding window aggregates (Window Functions `OVER()`), avoid data leakage via point-in-time joins, calculate user engagement metrics (DAU/MAU ratios, retention cohorts), and handle missing values (`COALESCE`) or un-nesting arrays (`EXPLODE / UNNEST`).

Coding for MLintermediatemust-know5 min

Implement Linear Regression from Scratch

Code linear regression from scratch with NumPy, a classic interview task.

Implement Linear Regression from Scratch demonstrates foundational machine learning coding fundamentals. The model fits a linear equation predicting continuous outputs by minimizing Mean Squared Error loss. The implementation covers weight and bias vector initialization, forward pass matrix multiplication, analytical prediction error calculation, and gradient descent backpropagation updates.

Responsible AI & Behaviouralintermediatemust-know5 min

Bias & Fairness in ML

How a model ends up treating groups of people unfairly, and what to do.

Model Bias and Fairness evaluate whether machine learning systems produce equitable predictions across protected sub-groups (e.g. race, gender, age). Bias enters pipelines through historical data sampling, proxy features (e.g. ZIP code encoding race), and label bias. Key fairness criteria—Demographic Parity, Equalized Odds, and Predictive Parity—are mathematically incompatible (Impossibility Theorem of Fairness), requiring explicit product trade-offs across pre-processing, in-processing, and post-processing mitigation techniques.

Responsible AI & Behaviouralintermediatemust-know4 min

Explainability: SHAP & LIME

Why did the model say that? Two popular ways to find out.

SHAP (SHapley Additive exPlanations) and LIME provide post-hoc model-agnostic explainability. SHAP is grounded in cooperative game theory, guaranteeing four essential axioms (Efficiency, Symmetry, Dummy, Additivity). SHAP computes a feature's marginal contribution across all feature subsets, ensuring local attributions sum up to (Model Output - Base Expected Value). TreeSHAP optimizes this to O(TL D²) for decision trees.

Responsible AI & Behaviouralintermediatemust-know5 min

Explaining a Model to a Non-Technical Exec

Explaining your model to executives in terms of money and risk.

Explaining a Model to a Non-Technical Exec evaluates communication clarity and business alignment. Technical executives care about revenue impact, risk mitigation, resource cost, and operational constraints rather than neural network mathematics or loss functions. Effective communication uses intuitive real-world analogies, translates metrics like Precision and Recall into dollars and risk, and focuses on actionable business outcomes.

Classical MLadvancedmust-know5 min

Gradient Boosting (XGBoost/LightGBM)

Each new tree fixes the last one's mistakes. It wins most tabular competitions.

Gradient boosting builds decision trees one after another, where each new tree tries to fix the mistakes the earlier trees are still making. Instead of reweighting examples like AdaBoost, each tree is trained directly on the leftover errors. A learning rate scales down every tree's contribution, so the model improves in small, careful steps. Tuned well, it is usually the most accurate method on tabular data. XGBoost, LightGBM and CatBoost are the popular versions, and they win most tabular competitions.

NLP & Transformersadvancedmust-know5 min

The KV Cache

Why chatbots stay fast as they write, and why they eat so much GPU memory.

When a model writes text one word at a time, each new word needs to look back at all the words before it. Without a cache, the model would recompute the same information for those earlier words at every single step. The KV cache stores each word's keys and values the first time they are calculated and reuses them, so each step only does the work for the newest word. Generation becomes much faster, but the cache grows with every word and can fill the GPU's memory.

LLMs & GenAIadvancedmust-know5 min

RLHF Explained

How chatbots learned which answers people actually prefer.

A pretrained model writes fluently but has no sense of which answers people actually prefer. RLHF teaches it that. First, people compare pairs of answers and pick the better one. Those choices train a separate reward model that learns to score any answer the way people would. Then the main model is fine-tuned to earn high scores from it, usually with an algorithm called PPO, plus a penalty for drifting too far from how it wrote before, so it cannot learn to game the scorer.

LLMs & GenAIadvancedmust-know5 min

LoRA & Parameter-Efficient Fine-Tuning

Fine-tune a huge model by training less than one percent of it.

Fine-tuning a large model normally means updating billions of weights, which needs a lot of GPU memory. LoRA freezes the original model and trains only two small extra matrices beside each layer, whose product is the adjustment the task needs. That cuts the number of trainable weights by around 99 percent. After training, the small matrices can be merged back in, so answers come just as fast as before. You can also keep one base model and swap small LoRA adapters for different tasks.

LLMs & GenAIadvancedmust-know5 min

Evaluating LLM Systems

Why grading an LLM is so much harder than grading a classifier.

Evaluating LLM Systems requires moving beyond classical ML metrics (Accuracy, F1) to handle non-deterministic, open-ended text generations. Evaluation methods form a 3-tier hierarchy: 1) Automated String & Overlap Metrics (ROUGE, BLEU, Exact Match), 2) Model-Based Evaluators (BERTScore, RAGAS, G-Eval), and 3) LLM-as-a-Judge or Human Preference Rating (Elo rating / A/B testing). A robust LLM evaluation pipeline combines continuous CI/CD automated test suites with golden dataset benchmarks.

Reinforcement Learningadvancedmust-know5 min

Proximal Policy Optimization

The workhorse of reinforcement learning, and the algorithm behind classic RLHF.

PPO is the go-to reinforcement learning algorithm, and it is the one used in classic RLHF for chatbots. Plain policy gradient methods can take one oversized update and wreck a policy that was working well. PPO prevents that by limiting how much the probability of any action can change in a single update. If an update would move it by more than a small amount, the extra change is ignored. That keeps learning steady, and it is far simpler than earlier methods with the same aim.

RecSys & Searchadvancedmust-know5 min

Two-Stage: Retrieval then Ranking

How apps pick your top ten from millions of items in a blink.

Production Recommender Systems (RecSys) use a multi-stage funnel architecture to balance latency and accuracy. Stage 1: Candidate Generation (Retrieval) filters millions of items down to top-100s in < 10ms using fast approximate vector search (ANN / Two-Tower models) or heuristics. Stage 2: Heavy Ranking scores and orders these 100s of candidates using complex multi-task deep learning models (DeepFM, DLRM). Stage 3: Re-ranking & Diversity applies business constraints, deduplication, position debiasing, and exploration.

RecSys & Searchadvancedmust-know5 min

Learning to Rank: Point, Pair, List

Getting the order right, not just the scores.

Learning to Rank (LTR) applies machine learning to construct optimal ranked lists of items for search queries or recommendation feeds. The three approaches differ in loss formulation: Pointwise predicts individual item relevance scores independently (Regression/BCE); Pairwise optimizes relative order between item pairs (RankNet, LambdaMART); Listwise optimizes metrics over the full ranked list simultaneously (ListNet, SoftRank). LambdaMART (Gradient Boosted Trees with Lambda gradients) remains the gold-standard algorithm for tabular ranking.

MLOps & Productionadvancedmust-know5 min

Point-in-Time Correct Feature Joins

Using only what was known at the time, or your model quietly cheats.

Point-in-Time Correctness (Time-Travel Join) ensures that training feature vectors contain only data available at or before event timestamp t. Joining features using standard SQL INNER JOIN or latest feature values causes Data Leakage (e.g. using user total 30-day spend computed today to train a model predicting a purchase 2 weeks ago). Modern Feature Stores (Feast, Hopsworks, Tecton) provide automated point-in-time joins using ASOF JOINs so a feature can never include information from after the event, which removes the most common source of leakage.

MLOps & Productionadvancedmust-know5 min

Debugging a Production Model Incident

Predictions suddenly look wrong in production. What do you check first?

Debugging a production ML incident requires a structured 5-step incident response playbook: 1) Immediate Mitigation (Triage & Fallback to rule-based baselines or previous model version), 2) Upstream Data & Pipeline Audit (Checking schema breaks, null rates, feature store lag), 3) Serving Infrastructure Verification (CPU/GPU utilization, OOMs, p99 latency), 4) Distribution Drift Analysis (PSI, feature distribution shifts), and 5) Post-Mortem & Safeguards (Adding automated schema contracts and integration tests).

Coding for MLadvancedmust-know5 min

Implement Self-Attention from Scratch

Code attention from scratch in PyTorch, line by line.

Implement Self-Attention from Scratch builds the core mechanism of Transformer models. Scaled Dot-Product Attention transforms input sequence vectors into Query, Key, and Value matrices. The algorithm calculates query-key similarity dot products, scales by the square root of key dimension, applies Softmax normalization, and computes weighted sums over Value vectors.

Math & Statisticsbeginner4 min

Bayes’ Theorem

How to update a belief with new evidence, and why gut feeling fails on rare events.

Bayes' theorem tells you how to update a belief when new evidence arrives. You start with how likely something was before, then adjust it by how well the evidence fits. The classic interview trap is the rare disease test. If only one person in a thousand has the disease, a test that is 99 percent accurate still flags far more healthy people than sick ones, simply because healthy people vastly outnumber the sick. In ML, the same idea powers Naive Bayes and Bayesian optimisation.

Math & Statisticsbeginner4 min

Central Limit Theorem

Why averages look like a bell curve, whatever shape the data started with.

The Central Limit Theorem (CLT) states that the sample mean of N independent, identically distributed (i.i.d.) random variables with finite variance approaches a Normal distribution N(μ, σ²/N) as N → ∞, regardless of the underlying population distribution. In ML and experimentation, CLT powers confidence intervals, hypothesis testing (z-test, t-test), A/B testing variance estimation, and mini-batch gradient descent stability.

Math & Statisticsbeginner4 min

Law of Large Numbers

Why averages settle down to the true value as you collect more data.

The Law of Large Numbers (LLN) guarantees that the sample mean X̄_N of N independent, identically distributed (i.i.d.) random variables converges to the true population expectation μ as N → ∞. The Weak LLN proves convergence in probability; the Strong LLN proves almost sure convergence. LLN underpins Monte Carlo integration, empirical risk minimization in ML, A/B testing sample size stability, and casino profitability.

Math & Statisticsbeginner4 min

Expectation & Variance

The two numbers that describe almost any distribution: where it sits and how spread it is.

Expectation E[X] is the probability-weighted average of all possible values of random variable X. Variance Var(X) = E[(X - E[X])²] measures expected squared deviation from the mean, with properties Var(aX + b) = a²Var(X). In machine learning, E[X] and Var(X) form the foundation of loss functions, MSE bias-variance decomposition, batch normalization, and weight initialization.

Math & Statisticsbeginner4 min

Covariance vs Correlation

Covariance tells you direction; correlation tells you direction and strength independent of scale.

Covariance Cov(X,Y) = E[(X - E[X])(Y - E[Y])] measures joint variability of two random variables, but its magnitude depends on measurement units. Pearson Correlation r = Cov(X,Y) / (σ_X σ_Y) normalizes covariance to [-1, +1], providing a scale-invariant measure of linear association. Key interview topics include Pearson vs Spearman correlation, covariance matrix construction, and correlation vs causation.

Math & Statisticsbeginner5 min

Distributions You Must Know

The handful of distributions that come up again and again in ML interviews.

A distribution describes how likely each possible outcome is, and picking the right one tells you which loss function to use. For counts: Bernoulli is one yes-or-no trial, binomial is the number of successes across several trials, and Poisson is how many events happen in a fixed time, like calls per hour. For measurements: the normal distribution is the familiar bell curve, exponential is the waiting time between events, and beta describes uncertainty about a probability itself, such as a click rate.

Math & Statisticsbeginner4 min

Type I vs Type II Errors

False alarms versus missed cases, and why cutting one usually raises the other.

Statistical decisions suffer from two distinct error modes: Type I Error (α - False Positive / False Alarm) occurs when we reject a true null hypothesis H₀. Type II Error (β - False Negative / Missed Detection) occurs when we fail to reject a false null hypothesis H₀. Statistical Power (1 - β) is the probability of correctly detecting a real effect. Balancing α and β is a cost trade-off driven by business risk.

Math & Statisticsbeginner4 min

Vector Norms (L1, L2, L∞)

Different ways to measure a vector's size, and why L1 makes weights zero.

A norm measures how big a vector is, and different norms measure size in different ways. The L1 norm adds up the absolute values, like walking city blocks, and as a penalty it pushes many weights to exactly zero, which is why Lasso picks features. The L2 norm is ordinary straight-line distance, and as a penalty it shrinks all weights smoothly, which is Ridge. The L-infinity norm is just the single largest value, useful when the worst case is what matters.

Math & Statisticsbeginner4 min

Dot Product & Cosine Similarity

How we measure whether two embeddings mean the same thing.

Dot Product and Cosine Similarity are the two core metrics for comparing vectors in machine learning. Dot product u · v = ∑ u_i v_i = ||u|| ||v|| cos(θ) combines both directional alignment and vector magnitude. Cosine similarity normalizes by vector lengths, measuring purely directional angle alignment cos(θ) on a [-1, 1] scale. When vectors are pre-normalized to unit length (||u|| = 1), Dot Product and Cosine Similarity become 100% mathematically identical.

Math & Statisticsbeginner4 min

Correlation vs Causation

Two things moving together does not mean one causes the other.

Correlation vs Causation is a foundational distinction in data science and empirical inference. Correlation measures linear statistical association between variables P(Y | X), while Causation measures the intervention effect P(Y | do(X)) of changing X directly. Correlation does not imply causation due to Spurious Correlations, Reverse Causality, and Unobserved Confounders.

Classical MLbeginner4 min

Supervised, Unsupervised & Self-Supervised

Learning with answers, without answers, and from the data itself.

Supervised Learning trains models on labeled input-output pairs (X, Y) for classification and regression. Unsupervised Learning finds inherent structural patterns, clusters, or lower-dimensional representations in unlabeled data (X). Self-Supervised Learning bridges the gap by automatically generating pseudo-labels from raw data structure (e.g. Next-Token Prediction, Masked Autoencoders), serving as the foundational engine for modern Foundation Models and LLMs.

Classical MLbeginner5 min

Decision Trees

A model that predicts by asking a series of yes-or-no questions.

A decision tree predicts by asking a series of yes-or-no questions, like is income above 50,000, then is age below 30. At each step it picks the question that best separates the classes, judged by how mixed each group is after the split. Trees handle curved patterns and mixed data types, need no feature scaling, and are easy to explain. Their weakness is overfitting: left to grow, a tree memorises the training data, so you limit its depth or prune it back.

Classical MLbeginner4 min

k-Nearest Neighbours

A model that does no training at all and just asks the nearest neighbours.

K-nearest neighbours does no real training at all. It simply stores every training example. To make a prediction, it finds the k examples closest to the new one, then takes a majority vote for classification or an average for regression. It is easy to understand and copes with odd-shaped boundaries. The downsides are speed and scale: every prediction compares against the whole dataset, distances need features on the same scale, and with many features distances stop being meaningful.

Classical MLbeginner4 min

Naive Bayes

A fast classifier built on an assumption that is almost always wrong, and still works.

Naive Bayes classifies by asking which class makes the observed features most likely, using Bayes' theorem. It is called naive because it assumes every feature is independent of the others once you know the class, which is almost never true. That shortcut makes it extremely fast and able to learn from very little data, and its rankings are often right even when its probabilities are off. It works well for text, like spam filtering. Smoothing stops one unseen word from forcing a probability to zero.

Classical MLbeginner5 min

k-Means Clustering

Grouping unlabelled data into k clusters by moving centres back and forth.

K-means groups data into k clusters without any labels. It places k centre points, assigns every point to its nearest centre, then moves each centre to the middle of the points assigned to it, repeating until nothing changes. It is fast and simple, but you must choose k yourself, a bad starting position can give a poor result, which the k-means++ starting method largely fixes, and it assumes clusters are roughly round and similar in size.

Classical MLbeginner4 min

Missing Data & Imputation

Why the reason data is missing decides how you should fill it.

Missing data degrades model quality and causes pipeline failures if unhandled. Missingness falls into three mechanisms: Missing Completely at Random (MCAR), Missing at Random (MAR), and Missing Not at Random (MNAR). Imputation techniques range from simple Mean/Median/Mode insertion and indicator flags to Iterative MICE (Multivariate Imputation by Chained Equations) and KNN imputation. Modern GBDTs (XGBoost, LightGBM) handle missing values natively during split finding.

Deep Learningbeginner4 min

Perceptron & the MLP

How tiny artificial neurons stack up into a deep neural network.

A Perceptron is the simplest artificial neuron. It takes multiple input numbers, multiplies each input by a weight number, adds a bias number, and passes the result through an activation step. Single perceptrons can only learn straight line decision boundaries. A Multi Layer Perceptron combines layers of connected neurons with non linear activation steps, allowing the network to learn complex curved patterns in data.

Deep Learningbeginner4 min

Choosing a Loss Function

The number your model tries to shrink, and how to pick the right one.

A Loss Function measures the numerical error between model predictions and true ground truth targets. For continuous regression, Mean Squared Error penalizes large outliers heavily while Mean Absolute Error provides robust median predictions. For classification, Binary Cross Entropy and Categorical Cross Entropy measure divergence between predicted probability distributions and target one hot vectors.

Deep Learningbeginner5 min

Data Augmentation

Getting more training data for free by flipping, cropping and tweaking what you have.

Data Augmentation artificially expands training datasets by applying domain specific transformations to existing data samples. In computer vision, techniques range from geometric spatial transforms (crops, flips, rotations) to color jitter and AutoAugment. In natural language processing, techniques include Back Translation, Synonym Replacement, and Contextual Word Insertion.

NLP & Transformersbeginner5 min

Word2Vec, GloVe & Embeddings

Turning words into numbers so that similar meanings sit close together.

Word embeddings turn each word into a list of a few hundred numbers, placed so that words with similar meanings sit close together. That lets a model see that king and queen are related, which a plain list of word IDs never could. Word2Vec learned these numbers by predicting a word from its neighbours, or the neighbours from the word. GloVe learned them from how often words appear together across a whole body of text. Both give each word one fixed meaning, whatever the sentence.

NLP & Transformersbeginner4 min

Text Classification Pipelines

Sorting text into categories, from spam filters to support tickets.

Text Classification assigns categorical labels to raw text documents (sentiment analysis, spam detection, intent routing). Pipelines evolved from classical TF-IDF with Logistic Regression or Naive Bayes to fine tuned BERT models and zero shot LLM prompts. Production pipelines require robust text cleaning, handling class imbalance, threshold calibration, and monitoring for domain drift.

NLP & Transformersbeginner5 min

TF-IDF & BM25

The keyword scoring behind classic search engines, and why it still matters.

TF-IDF and BM25 are foundational lexical keyword search algorithms. TF-IDF weights words by Term Frequency (how often a word appears in a document) multiplied by Inverse Document Frequency (how rare the word is across the corpus). Okapi BM25 improves TF-IDF by adding Term Frequency Saturation and Document Length Normalization, serving as the default retrieval algorithm in Elasticsearch and Lucene.

NLP & Transformersbeginner4 min

Stemming, Lemmatization & Stopwords

Cleaning messy text before older NLP models can use it.

Text Preprocessing prepares raw natural language text for machine learning algorithms. Traditional NLP pipelines remove noise using Lowercasing, Stopword Removal (filtering out common filler words like 'the' or 'is'), Stemming (chopping word suffixes using heuristic rules), and Lemmatization (mapping words to valid dictionary roots). Modern Transformer language models use raw subword tokenization (BPE), rendering manual text preprocessing obsolete.

LLMs & GenAIbeginner5 min

Why Next-Token Prediction Works

Guessing the next word sounds trivial. It is how these models learn almost everything.

Next Token Prediction is the foundational self supervised training objective for Large Language Models. By predicting the probability distribution of the single next token given all preceding context tokens P(x_t | x_1...x_t-1), language models are forced to compress vast internet world knowledge, grammar, logic, and reasoning into model parameters. Scaling next token prediction across billions of parameters unlocks emergent zero shot capabilities, in context learning, and instruction following.

LLMs & GenAIbeginner5 min

Prompt Engineering That Works

Simple ways to write prompts that get more accurate, reliable answers.

Prompt Engineering is the practice of designing input prompt structures to guide Large Language Model behavior effectively. Key techniques include assigning System Personas, providing explicit Delimiters, setting structural Output Constraints (JSON / Markdown), using Negative Constraints, and employing Few-Shot Exemplars. Systematic prompt engineering turns unpredictable LLM responses into reliable, production-ready outputs.

LLMs & GenAIbeginner5 min

Zero-shot, Few-shot & In-Context Learning

Why showing a model a few examples often beats explaining the task.

Zero-Shot, Few-Shot, and In-Context Learning (ICL) describe methods for directing LLM task performance using context prompts without modifying model weights. Zero-Shot prompting asks a model to execute a task using instructions alone. Few-Shot prompting provides K input-output exemplars in the prompt context. In-Context Learning is an emergent property where self attention mechanisms process exemplars in forward passes to infer task patterns dynamically.

LLMs & GenAIbeginner5 min

Temperature, Top-p & Sampling

The settings that decide whether a model plays it safe or gets creative.

When a model writes, it gives every possible next word a probability, and these settings control how it picks from that list. Temperature reshapes the list: near zero it almost always takes the top word, which is predictable, while above one unlikely words get more chances, which is creative but riskier. Top-k allows only the k most likely words. Top-p allows the smallest group whose probabilities add up to p, so the group shrinks when the model is sure and grows when it is not.

Computer Visionbeginner5 min

Image Augmentation Strategies

Flipping, cropping and recolouring images so a model sees more variety.

Image Augmentation expands training dataset diversity by applying synthetic transformations to input images. Traditional augmentations include random cropping, flipping, color jittering, and rotation. Advanced regularizers like Mixup blend two images and their labels linearly: x = λ x_A + (1-λ) x_B. CutMix patches a rectangular region of image B into image A, setting target label proportions equal to patch area. RandAugment automates hyperparameter search by applying a small sequence of randomly sampled operations with uniform magnitude.

Computer Visionbeginner4 min

Resizing, Normalization & Colour Spaces

Resizing and normalising images the way your model expects, or it quietly fails.

Image Preprocessing converts raw camera pixels into clean, standardized input tensors for computer vision models. Key operations include Aspect Ratio Preserving Resizing (padding vs letterboxing), Channel Normalization using ImageNet mean and standard deviation, and Color Space Conversions (RGB, BGR, HSV, Lab). Correct preprocessing prevents aspect ratio distortion and matches pretraining feature statistics.

RecSys & Searchbeginner4 min

Content-Based Filtering

Recommending things similar to what you already liked.

Content-Based Filtering recommends items to a user by matching item feature attributes (genres, text tags, author, brand, TF-IDF vectors) against a user feature profile built from past interactions. Unlike Collaborative Filtering, Content-Based Filtering operates independently across users, enabling instant recommendations for new items with zero interaction history (solving Item Cold-Start). Disadvantages include lack of serendipity (filter bubble) and inability to leverage collective user wisdom.

ML System Designbeginner5 min

Why You Propose a Baseline First

Build the simple model first. It often wins, and it always tells you something.

Proposing a Baseline First is a fundamental best practice in machine learning engineering and system design interviews. Before building complex 100 layer Transformer or GNN architectures, start with a simple, interpretable baseline (e.g. Heuristic Rules, Logistic Regression, BM25, or Most Popular items). Baselines validate data pipelines, set lower bound performance benchmarks, provide fast fallback options, and quantify ROI improvements of complex models.

MLOps & Productionbeginner5 min

The End-to-End ML Lifecycle

Training the model is the short part. Here is everything around it.

The End to End Machine Learning Lifecycle spans the complete iterative lifecycle of AI products. The cycle moves continuously through Problem Formulation, Data Ingestion and Validation, Feature Engineering, Model Training and Evaluation, Deployment and Serving, and Real-Time Production Monitoring. Deployed models require ongoing retraining loops to adapt to changing real world environments.

MLOps & Productionbeginner5 min

Experiment Tracking & Reproducibility

Keeping hundreds of training runs organised so you can tell what worked.

Experiment Tracking logs parameters, evaluation metrics, data versions, and output artifacts during machine learning development. Without systematic tracking, teams lose track of which hyperparameters or dataset splits produced the best model checkpoint. Tools like MLflow, Weights and Biases, and Neptune record loss curves and metrics automatically to enable fast model comparison and reproducibility.

MLOps & Productionbeginner5 min

Model Registries & Promotion

One shelf for every model version, with a record of where each came from.

A Model Registry is a centralized repository for storing, versioning, and managing machine learning model artifacts. It tracks complete model lineage from training code and datasets down to compiled binaries. Model registries govern stage promotion workflows, transitioning candidate models through Experimental, Staging, Production, and Archived lifecycle stages with audit trails.

MLOps & Productionbeginner5 min

Model Cards & Documentation

A nutrition label for models: what they are for and where they fail.

A model card is a short, standard document that ships with a machine learning model, a bit like a nutrition label. It says what the model is for and what it should not be used for, what data it was trained on, and how well it performs, broken down across different groups of people rather than as one overall number. It also lists known limitations and ethical concerns. Model cards make audits easier and show where a model is likely to fail.

Metrics & Evaluationbeginner5 min

Reading a Confusion Matrix

The four boxes behind almost every classification metric.

Reading a Confusion Matrix is a fundamental skill for evaluating classification models. A Confusion Matrix is a grid comparing predicted class labels against true ground truth labels across True Positives, False Positives, True Negatives, and False Negatives. It reveals specific error types, forming the foundation for calculating Precision, Recall, Specificity, and F1 score.

Metrics & Evaluationbeginner5 min

MSE, MAE, RMSE, R²

MSE, MAE, RMSE and R-squared: which error measure to use, and when.

Regression Metrics evaluate continuous numeric prediction models. Mean Absolute Error (MAE) measures average error magnitude robustly against outliers. Mean Squared Error (MSE) and Root Mean Squared Error (RMSE) penalize large prediction errors heavily due to squaring. R-squared (Coefficient of Determination) measures the proportion of target variance explained by the model compared to a simple mean baseline.

Metrics & Evaluationbeginner4 min

Splitting Data Without Cheating

How to split data so your test score predicts real-world performance.

Partitioning data into Training, Validation, and Test sets is the first defense against overfitting and data leakage. Standard Random Splits work for independent i.i.d. samples. Stratified Splits preserve class distribution ratios for imbalanced data. Group Splits (GroupKFold) prevent data leakage when multiple rows originate from the same user/patient. Temporal Splits (TimeSeriesSplit) enforce chronological ordering for time-dependent data.

SCROLL · SAVE · TAP TO GO DEEPER