Memory tricks that make machine learning algorithms click
From supervised to reinforcement learning -- these memory tricks lock in every major ML algorithm, the bias-variance tradeoff, and the workflow that makes models actually work.
Or continue to the sub-topics below for more specialized Study Rooms and Forums
Machine Learning
Memory Tricks
Proven Mnemonics & Acronyms — fast to learn, hard to forget.
Star Most Tested
SPLIT -- Select, Prepare, Learn, Interpret, Test -- the 5-step ML workflow
THE ML PROJECT WORKFLOW
Every ML project follows this repeatable process -- know it cold
Select the right algorithm for your problem type. Prepare data: clean, normalize, handle missing values, encode categoricals, split train/test. Learn: train the model -- algorithm finds optimal parameters. Interpret: examine what was learned. Test: evaluate on held-out test set -- never seen during training. Performance on test data is the only honest measure of model quality.
Select
Match algorithm to problem type (classification, regression, clustering)
Prepare
~80% of ML work -- clean, normalize, encode, split
Learn
Train on training set -- find optimal parameters
Test
Held-out test set -- the only honest performance measure
Regression
LINE -- Linear regression predicts a NUMBER. Logistic predicts a CATEGORY.
THE NAMING TRAP -- LOGISTIC REGRESSION IS A CLASSIFIER
Linear predicts a number. Logistic predicts a category. Despite the name.
Linear Regression: y = mx + b, minimizes squared errors, predicts continuous values (house price, temperature). Logistic Regression: despite the name, used for CLASSIFICATION -- uses sigmoid function to output probability 0-1. Decision boundary at 0.5. Above = positive class. Below = negative class. This distinction appears on virtually every ML exam.
Linear Regression
Continuous output -- house price, temperature, salary
Logistic Regression
CLASSIFICATION despite the name -- outputs probability 0-1
Sigmoid function
Squashes to 0-1: s(z) = 1/(1+e^-z)
Decision boundary
0.5 threshold -- above=positive, below=negative
Decision Trees
TREE -- Test feature, Recurse on subsets, End at leaf, Ensemble to improve
DECISION TREE to RANDOM FOREST to XGBOOST
Single trees overfit. Ensembles are among the most powerful ML algorithms.
Decision Trees split data by feature questions using Gini impurity or Information Gain. Prone to overfitting alone. Random Forest (bagging): parallel trees on random data and feature subsets -- reduces variance. XGBoost (boosting): sequential trees, each corrects previous errors -- dominant for tabular data competitions. No feature scaling needed for tree-based methods.
Gini impurity
Probability of misclassifying a random sample -- used to pick splits
Boosting -- sequential, each tree corrects prior errors
No scaling needed
Tree-based methods are scale-invariant
K-Nearest Neighbors
K-NN -- K Neighbors vote, No training needed, Nearest wins
LAZY LEARNER -- ALL COMPUTATION AT PREDICTION TIME
K-NN has no training phase -- it simply memorizes the training set
Find K closest training examples (Euclidean distance), take majority vote (classification) or average (regression). Always normalize -- large-range features dominate distance. Curse of dimensionality: too many features makes distance meaningless. Choose K with cross-validation. K=1 overfits. Large K underfits.
Always normalize
Distance is meaningless without feature scaling
Curse of dimensionality
Many features = sparse space = nearest neighbor meaningless
K=1
Overfits -- very sensitive to noise
Choose K
Cross-validate -- odd K for binary classification avoids ties
SVM
SVM = finds the WIDEST STREET between classes
MAXIMUM MARGIN CLASSIFIER
Support vectors are the training points closest to the boundary -- they define everything
SVM finds the hyperplane that maximally separates classes. Wider margin = better generalization. Kernel trick: maps data to higher dimensions where linearly separable -- RBF kernel handles nonlinear data. C parameter: low C = wider margin, more misclassifications tolerated. High C = narrow margin, fewer misclassifications. Best for high-dimensional sparse data.
Maximum margin
Wider margin = better generalization to new data
Kernel trick
Map to higher dimension where data IS linearly separable
C parameter
Low C = wide margin (tolerant). High C = narrow margin (strict).
Best for
Text classification and high-dimensional sparse data
K-Means Clustering
K-MEANS -- K clusters, Move centroids, Assign nearest, Repeat until stable
UNSUPERVISED CLUSTERING -- GROUP WITHOUT LABELS
Use the elbow method to find optimal K -- plot inertia vs K, pick the bend
Steps: choose K, randomly initialize K centroids, assign each point to nearest centroid, recalculate centroids as cluster means, repeat until stable. Elbow method: plot inertia vs K, choose where improvement slows. DBSCAN alternative: finds arbitrary-shaped clusters and outliers automatically without specifying K.
Elbow method
Plot inertia vs K -- choose where improvement slows
Weakness
Needs K in advance, sensitive to outliers, assumes spherical clusters
DBSCAN
No K needed, finds arbitrary shapes, detects outliers
Scale first
K-Means uses distance -- normalize all features
Feature Engineering
SCALE before you TRAIN -- unscaled features ruin distance-based algorithms
NORMALIZE and STANDARDIZE and ENCODE and REDUCE
Always split data BEFORE fitting any transformers to prevent data leakage
Normalization (Min-Max): scales to 0-1. Standardization (Z-score): mean=0, std=1. Scale for: K-NN, SVM, neural networks, PCA. NOT for: tree-based methods. One-hot encoding: categoricals to binary columns. Label encoding: integers to categories -- only when ordinal. PCA: reduce dimensions by keeping directions of maximum variance. Golden rule: fit transformers on training data only.
Decision trees, Random Forest, XGBoost -- scale-invariant
One-hot encoding
Red/Green/Blue becomes 3 binary columns
PCA
Keep maximum variance directions -- reduce noise and computation
Naive Bayes
NAIVE = assumes all features INDEPENDENT -- wrong but works surprisingly well
BAYES THEOREM WITH AN INDEPENDENCE ASSUMPTION -- FAST AND EFFECTIVE
For text classification the independence assumption holds approximately -- that's enough
P(class|features) proportional to P(class) times product of P(feature|class). Despite independence assumption being almost always violated, it works well for text -- word frequencies are roughly independent given class. Gaussian NB: continuous features. Multinomial NB: word counts. Laplace smoothing: add 1 to all counts to prevent zero probabilities.
Gaussian NB
Assumes continuous features follow Gaussian distribution
Multinomial NB
For word counts -- text classification, spam detection
Laplace smoothing
Add 1 to counts -- prevents zero probability killing the product
RLHF is how ChatGPT and Claude are aligned -- human feedback trains a reward model
Agent: learner. State: current situation. Action: choice made. Reward: feedback signal. Policy: strategy mapping states to actions. Goal: maximize expected cumulative reward. Exploration vs exploitation. Q-learning: learns value of state-action pairs. RLHF (Reinforcement Learning from Human Feedback): human raters rank outputs, reward model trained, RL maximizes it -- standard for aligning LLMs.
Agent
Learner that takes actions and receives rewards
Policy
Strategy: given state s, what action a to take
Q-learning
Learns Q(s,a) = expected cumulative reward from state s taking action a
RLHF
Human rankings + reward model + RL = aligned ChatGPT/Claude
NEVER SHUFFLE TIME SERIES DATA -- ALWAYS SPLIT CHRONOLOGICALLY
Future data cannot predict the past -- chronological order must be preserved
Trend: long-term direction. Seasonality: regular repeating patterns (daily, weekly, yearly). Autocorrelation: current value correlates with its own past values. Cycle: irregular multi-year patterns. NEVER shuffle before splitting -- always chronological. Classic models: ARIMA. Modern: LSTMs, Temporal CNNs, Transformer-based forecasters.
Current value correlates with past values (lag-1, lag-2...)
Never shuffle
Always split chronologically -- future cannot predict past
Anomaly Detection
RARE events are ISOLATED -- Isolation Forest finds anomalies with fewer random splits
DETECT THE UNUSUAL WITHOUT LABELED ANOMALY EXAMPLES
Train on normal data only -- anomalies stand out by being hard to reconstruct
Isolation Forest: anomalies isolated by fewer random splits (short path = anomaly) -- fast, scalable, no distance metric needed. Statistical: z-score, flag beyond N standard deviations. Autoencoder: train on normal data only, flag high reconstruction error points as anomalies. Applications: fraud detection, network intrusion, manufacturing defects, medical outliers.
Isolation Forest
Short path to isolate = anomaly. Fast, scalable.
Z-score
Simple -- flag points beyond 2-3 standard deviations
Autoencoder
Train on normal data -- anomalies cannot be reconstructed well
Applications
Fraud, network intrusion, defects, medical outliers
AI BUILDING AI -- NEURAL ARCHITECTURE SEARCH FOUND EFFICIENTNET
AutoML automates the tuning, not the thinking -- still need good problem framing
AutoML tools: Google AutoML (cloud, no-code), H2O AutoML (open-source), Auto-sklearn. NAS (Neural Architecture Search): discovered EfficientNet -- outperformed human-designed networks. Active Learning: model queries the most uncertain examples for labeling -- reduces labeling cost by 5-10x. Limitations: still requires clean data, correct evaluation metric, good problem definition.
Google AutoML
Cloud-based, no-code, requires little ML expertise
H2O AutoML
Open-source, competitive with cloud options on tabular data
NAS
Found EfficientNet -- better than human-designed CNN architectures
Active Learning
Query uncertain examples -- 5-10x more label-efficient
🎯 Exam Favorite
SUL — Supervised Uses Labels, Unsupervised Loses Labels
THE LABEL RULE — NEVER MIX THEM UP AGAIN
Supervised vs Unsupervised learning in one sentence
Supervised learning: every training example has a label (the right answer). The model learns to predict labels. Unsupervised learning: no labels at all — the model finds hidden structure on its own. Think of it as school (supervised — teacher gives answers) vs exploration (unsupervised — figure it out yourself). The label is the dividing line between them.
🧠 Vivid Story
Gradient Descent = Rolling a BALL DOWN A HILL to find the lowest point
THE HILL METAPHOR — HOW MODELS ACTUALLY LEARN
Gradient descent explained with one unforgettable image
Imagine you're blindfolded on a hilly landscape. Your goal is to reach the lowest valley (minimum loss). You feel the slope under your feet and take a small step downhill. Repeat thousands of times. That's gradient descent — the model checks which direction reduces error, takes a small step that direction, and repeats until it can't go lower. Learning rate = how big each step is. Too big = overshoot. Too small = takes forever.
🔑 Key Distinction
REWARD DOG — Reinforcement Learning is a dog learning tricks for treats
AGENT · ENVIRONMENT · REWARD — the three RL components
Reinforcement learning — the reward dog story
Reinforcement learning has three parts: an Agent (the dog/AI), an Environment (the world it acts in), and a Reward signal (treat or punishment). The agent takes actions, receives rewards or penalties, and learns which actions maximize total reward over time. No labels needed — just trial, error, and feedback. This is how AlphaGo beat world chess champions and how robots learn to walk.
💡 Concept Anchor
CROSS-VALIDATION = Taking the SAME EXAM multiple times with different questions each round
K-FOLD — ROTATE THE TEST SET EVERY ROUND
K-fold cross-validation — why one test isn't enough
K-fold cross-validation splits data into K equal chunks. In each round, one chunk is the test set and the rest train the model. Rotate K times so every chunk gets tested once. Average the K scores for a reliable estimate. Why? One test split might be lucky or unlucky. K-fold gives a fair average across many splits. K=5 or K=10 are standard. Think of it as rotating who grades your exam to get a fair average score.
📅 Quick Reference
FOREST BEATS TREE — Ensemble methods always outperform single models
WISDOM OF CROWDS IN MACHINE LEARNING
Why ensemble methods like Random Forest win
A single decision tree can overfit badly. A Random Forest grows hundreds of trees on random data subsets and averages their predictions. More diverse opinions = more stable result. This is ensemble learning — combining many weak learners into one strong learner. Bagging (Random Forest) averages parallel models. Boosting (XGBoost) trains models sequentially, each fixing the last one's errors. Either way: the forest always beats the tree.
⭐ Most Important
BULLSEYE — Low Bias + Low Variance = dead center every shot
BIAS = AIM · VARIANCE = SPREAD
Bias-Variance Tradeoff — the most tested ML theory concept
Picture a dartboard. Bias = how far from the bullseye your average shot lands (systematic error — wrong aim). Variance = how spread out your shots are (inconsistency). High Bias = underfitting — model too simple, misses the pattern every time. High Variance = overfitting — model too complex, nails training data but wild on new data. The goal: low bias AND low variance. Increasing model complexity reduces bias but raises variance — the unavoidable tradeoff.
High Bias
Underfitting — model too simple, misses real patterns (linear model on curved data)
High Variance
Overfitting — model memorizes training noise, fails on new data
Sweet spot
Right complexity — generalizes well to unseen data
🐍 Code
from sklearn.model_selection import validation_curve train_scores, val_scores = validation_curve(model, X, y, param_name='max_depth', param_range=range(1,20)) # Plot to see the bias-variance tradeoff visually
🎯 Exam Favorite
OVERFIT = Memorized the TEXTBOOK · UNDERFIT = Didn't study at all
TRAINING ERROR vs VALIDATION ERROR GAP
Overfitting vs Underfitting — spotted by the training/validation gap
Overfitting: training accuracy very high, validation accuracy much lower — the model memorized the training set including its noise. Like a student who memorized every practice exam verbatim but can't handle new questions. Underfitting: both training AND validation accuracy are low — the model hasn't learned the pattern at all. The diagnostic: plot learning curves. A big gap between training and validation = overfitting. Both curves low and flat = underfitting.
Overfitting fix
More data, regularization (L1/L2), dropout, simpler model, pruning
Underfitting fix
More complex model, more features, longer training, remove regularization
Diagnostic
Learning curve: plot train vs validation score against training set size
🐍 Code
from sklearn.model_selection import learning_curve train_sizes, train_scores, val_scores = learning_curve(model, X, y, cv=5) # Big gap between curves = overfitting. Both low = underfitting.
🔑 Key Distinction
BAGGING = PARALLEL trees vote · BOOSTING = SEQUENTIAL trees correct each other
RANDOM FOREST vs XGBOOST — know both cold
Bagging vs Boosting — ensemble methods compared
Bagging (Bootstrap Aggregating): trains many models IN PARALLEL on random data subsets, averages their predictions. Reduces variance. Random Forest is the gold standard. Boosting: trains models SEQUENTIALLY — each new model focuses on examples the previous one got wrong. Reduces bias. XGBoost, LightGBM, and AdaBoost are the most powerful implementations. Rule of thumb: Random Forest when you need speed and reliability. XGBoost when you need maximum accuracy on tabular data.
Bagging
Parallel, reduces variance, Random Forest — fast, robust, hard to overfit
Boosting
Sequential, reduces bias, XGBoost — highest accuracy on tabular data
🐍 Bagging code
from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(n_estimators=100, random_state=42) rf.fit(X_train, y_train)
🐍 Boosting code
from xgboost import XGBClassifier xgb = XGBClassifier(n_estimators=100, learning_rate=0.1) xgb.fit(X_train, y_train)
💡 Concept Anchor
L1 KILLS features · L2 SHRINKS features — regularization is a tax on complexity
LASSO vs RIDGE — two flavors of the same cure
L1 vs L2 Regularization — preventing overfitting by penalizing weights
Regularization adds a penalty to the loss function for large weights — taxing the model for complexity. L1 (Lasso): penalty = sum of absolute values of weights. Drives unimportant weights to exactly zero — built-in feature selection. L2 (Ridge): penalty = sum of squared weights. Shrinks all weights toward zero but rarely to exactly zero. Elastic Net combines both. Use L1 when you suspect only a few features matter. Use L2 when all features contribute something. Lambda controls the penalty strength.
L1 (Lasso)
Kills irrelevant features — sparse solution, automatic feature selection
L2 (Ridge)
Shrinks all features — smooth solution, no feature elimination
Elastic Net
L1 + L2 combined — best of both when unsure
🐍 Code
from sklearn.linear_model import Lasso, Ridge, ElasticNet lasso = Lasso(alpha=0.1) # L1 — kills features ridge = Ridge(alpha=1.0) # L2 — shrinks features enet = ElasticNet(alpha=0.1, l1_ratio=0.5) # both
0
Correct
0
Missed
0
Remaining
What does this mean / stand for?
0
Correct
0
Wrong
0
Remaining
🔗 Related Sub-Subjects
🕸️ Neural Networks
How neurons, layers, backpropagation, and activation functions build on ML fundamentals.
Q: What is the difference between a parameter and a hyperparameter?
A: Parameters are learned from data during training (e.g., weights in a neural network). Hyperparameters are set before training and control the learning process (e.g., learning rate, K in K-NN, number of trees). You tune hyperparameters; the model learns parameters.
Q: Why can't you use the test set to tune hyperparameters?
A: The test set must remain unseen until final evaluation. Using it to tune causes data leakage — you'd be optimizing for that specific test set, giving falsely inflated performance. Use the validation set or cross-validation for tuning.
Q: When would you choose Random Forest over XGBoost?
A: Random Forest when you need fast training, easy deployment, and robustness with minimal tuning. XGBoost when you need maximum accuracy on tabular data and have time to tune. XGBoost wins most Kaggle competitions; Random Forest wins in production reliability.
Q: What is the curse of dimensionality?
A: As the number of features increases, data becomes increasingly sparse — all points become roughly equidistant. Distance-based algorithms (K-NN, K-means, SVM) degrade dramatically. Fix with PCA, feature selection, or dimensionality-robust algorithms.
Q: Explain L1 vs L2 regularization.
A: L1 (Lasso) adds absolute weight values as penalty — drives unimportant weights to exactly zero, performing automatic feature selection. L2 (Ridge) adds squared weights — shrinks all weights toward zero but rarely eliminates them. L1 for sparse solutions; L2 when all features likely contribute.
Q: What does the learning rate control in gradient descent?
A: The learning rate controls the step size when moving down the loss curve. Too large: overshoots the minimum and diverges. Too small: training takes forever. Solution: learning rate scheduling (start large, decay over time) or adaptive optimizers like Adam that adjust it automatically.