ML Basics Cheat Sheet β€” Supervised, Unsupervised, Loss, Bias-Variance | Dataplexa
← Back to Cheat Sheets
Sheet icon

ML Basics Cheat Sheet

Supervised Β· Unsupervised Β· Loss Functions Β· Bias-Variance Β· Regularization Β· Model Workflow

Sheet 1 of 4 Machine Learning Beginner–Intermediate Printable

What is Machine Learning?

Definition
Core Idea
Learn f: X β†’ Y from data, without explicit rules
X = input features Β· Y = target output Β· f = learned function (model)
TypeLabels?GoalExample
Supervisedβœ… YesPredict Y from XSpam detection, price prediction
Unsupervised❌ NoFind structure in XCustomer segmentation, anomaly detection
Semi-supervisedPartialLeverage few labels + many unlabeledImage classification with sparse labels
ReinforcementRewardsMaximize cumulative rewardGame playing, robotics
Key insight: ML finds patterns automatically β€” the model improves as it sees more data.

Supervised Learning

Core
🏷 Classification
  • Output: discrete class
  • Binary: yes/no, spam/ham
  • Multi-class: digit 0–9
  • Metric: Accuracy, F1, AUC
  • Algorithms: LR, SVM, Trees, KNN
πŸ“ˆ Regression
  • Output: continuous value
  • House price, temperature
  • Stock forecast, demand
  • Metric: MSE, RMSE, MAE, RΒ²
  • Algorithms: Linear Reg, SVR, Trees
General Training Objective
minimize L(Ε·, y) over model parameters ΞΈ
Ε· = model prediction Β· y = true label Β· L = loss function
Tip: Always split data into train / validation / test before fitting β€” never evaluate on training data.

Unsupervised Learning

Core
TaskGoalCommon Algorithms
ClusteringGroup similar data pointsK-Means, DBSCAN, Hierarchical
Dimensionality ReductionCompress features, remove noisePCA, t-SNE, UMAP, Autoencoders
Density EstimationModel data distributionGMM, KDE, Normalizing Flows
Anomaly DetectionIdentify outliersIsolation Forest, One-Class SVM
Association RulesFind co-occurrence patternsApriori, FP-Growth
Use case: When labels are expensive or unavailable β€” explore structure in raw data first.

Loss Functions

Math

Loss measures how far predictions are from the truth. Training minimizes it.

LossFormulaUse When
MSE1/n Β· Ξ£(yα΅’ βˆ’ Ε·α΅’)Β²Regression, penalizes large errors heavily
MAE1/n Β· Ξ£|yα΅’ βˆ’ Ε·α΅’|Regression, robust to outliers
HuberMSE if |e|≀δ, else MAERegression, balance of MSE+MAE
Binary Cross-Entropyβˆ’[yΒ·log(Ε·) + (1βˆ’y)Β·log(1βˆ’Ε·)]Binary classification
Categorical Cross-Entropyβˆ’Ξ£ yα΅’ Β· log(Ε·α΅’)Multi-class classification
Hingemax(0, 1 βˆ’ yΒ·Ε·)SVM classification
Log Loss (Binary Cross-Entropy) Intuition
L = βˆ’(yΒ·log p + (1βˆ’y)Β·log(1βˆ’p))
p = predicted probability Β· heavily penalizes confident wrong predictions

Bias–Variance Tradeoff

Theory
Error Decomposition
Total Error = BiasΒ² + Variance + Irreducible Noise
Irreducible noise = inherent randomness in data β€” cannot be removed
⬆ High Bias (Underfitting)
  • Model too simple
  • High train & test error
  • Misses patterns in data
  • Fix: add complexity, more features
⬆ High Variance (Overfitting)
  • Model too complex
  • Low train, high test error
  • Memorizes training noise
  • Fix: regularize, get more data
Sweet spot: Choose the simplest model that generalizes well to unseen data.

Overfitting vs Underfitting

Diagnosis
SignalUnderfittingOverfitting
Train errorHigh ❌Low βœ…
Val/Test errorHigh ❌High ❌
Train–Val gapSmallLarge
Root causeToo simpleToo complex
Fix UnderfittingFix Overfitting
Increase model complexityAdd regularization (L1/L2)
Add more featuresReduce features / use selection
Train longer / more epochsEarly stopping
Remove strong regularizationCollect more training data
Try more powerful algorithmDropout (neural networks)

Regularization

Technique
Regularized Loss
L_reg = L(Ε·, y) + Ξ» Β· Ξ©(ΞΈ)
Ξ» = regularization strength Β· Ξ©(ΞΈ) = penalty on model weights
MethodPenalty Ξ©(ΞΈ)Effect
L2 (Ridge)Ξ£ ΞΈα΅’Β²Shrinks all weights β€” never zero
L1 (Lasso)Ξ£ |ΞΈα΅’|Pushes weights to zero β€” sparse model
ElasticNetΞ±Β·L1 + (1βˆ’Ξ±)Β·L2Combines both β€” flexible
DropoutRandom neuron offNeural nets β€” prevents co-adaptation
Early StoppingStop at min val lossImplicit regularization β€” cheap
Ξ» tuning: Too small β†’ still overfits. Too large β†’ underfits. Use cross-validation to find the sweet spot.

Data Splits & Cross-Validation

Workflow
SplitTypical %Purpose
Training set60–80%Fit model parameters
Validation set10–20%Tune hyperparameters, detect overfitting
Test set10–20%Final unbiased performance estimate
k-Fold Cross-Validation
CV Score = (1/k) Β· Ξ£α΅’ Score(fold i)
k=5 or k=10 common Β· Stratified k-Fold preserves class proportions
TechniqueBest For
k-Fold CVGeneral β€” balanced between bias & variance
Stratified k-FoldImbalanced classification
Leave-One-Out (LOO)Very small datasets
Time-Series SplitTemporal data β€” no future leakage
Never let test data touch training or hyperparameter tuning β€” it's for final evaluation only.

The Machine Learning Workflow

End-to-End
  1. Define the problem β€” Classification or regression? What is success? Which metric?
  2. Collect & explore data (EDA) β€” distributions, missing values, outliers, correlations
  3. Preprocess & clean β€” handle nulls, encode categoricals, fix data types
  4. Feature engineering β€” create, transform, and select informative features
  5. Split data β€” train / validation / test (or k-fold) β€” split before any fitting
  6. Choose & train baseline model β€” simple model first (linear reg, decision tree)
  1. Evaluate on validation set β€” accuracy, F1, RMSE, AUC-ROC etc.
  2. Tune hyperparameters β€” Grid Search, Random Search, or Bayesian optimization
  3. Handle overfitting/underfitting β€” regularization, data augmentation, feature selection
  4. Train final model β€” on train + validation; evaluate once on test set
  5. Interpret & explain β€” SHAP values, feature importance, partial dependence plots
  6. Deploy & monitor β€” serve predictions, watch for data/concept drift
Golden rule: Start simple. A strong baseline + good feature engineering often beats a complex model with raw data.

Hyperparameter Tuning

Optimization
StrategyHowBest For
Grid SearchTry all combinations in gridSmall param spaces
Random SearchSample randomly from distributionsLarger param spaces
Bayesian OptimizationModel performance surface, sample smartlyExpensive models
Halving / SuccessiveQuickly eliminate bad configsLarge candidate sets
sklearn β€” Grid Search CV
from sklearn.model_selection import GridSearchCV

params = {'max_depth': [3, 5, 10],
           'n_estimators': [50, 100, 200]}
gs = GridSearchCV(model, params,
                   cv=5, scoring='f1')
gs.fit(X_train, y_train)
best = gs.best_params_
Random Search tip: Random Search finds good hyperparameters ~10Γ— faster than Grid Search for most problems (Bergstra & Bengio 2012).

Feature Scaling

Preprocessing
MethodFormulaRangeUse When
Min-Max Normalization(x βˆ’ min) / (max βˆ’ min)[0, 1]Bounded output needed, no outliers
Standardization (Z-score)(x βˆ’ ΞΌ) / Οƒ~(βˆ’3, 3)Gaussian-based algos, with outliers
Robust Scaler(x βˆ’ median) / IQRUnboundedHeavy outliers present
Log Transformlog(x + 1)UnboundedRight-skewed data (income, counts)
sklearn Scaling Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

pipe = Pipeline([
  ('scale', StandardScaler()),
  ('model', LogisticRegression())
])
pipe.fit(X_train, y_train)
Critical: Fit scaler on training data only β€” transform both train and test using training statistics. Never fit on test data.

Imbalanced Data

Data Issue
StrategyHow It WorksWhen
Oversampling (SMOTE)Generate synthetic minority samplesSmall dataset, severe imbalance
UndersamplingRemove majority class samplesLarge dataset
Class weightsPenalize minority misclassification moreQuick, no data change
Threshold tuningAdjust decision boundary (default 0.5)Post-training
Ensemble methodsBalancedRF, EasyEnsembleGeneral-purpose
class_weight in sklearn
LogisticRegression(class_weight='balanced')
RandomForestClassifier(class_weight='balanced')

# Or specify manually
SVC(class_weight={0: 1, 1: 10})
Avoid accuracy! 95% accuracy on 95/5 split = model predicts majority always. Use F1, AUC-ROC, or Precision-Recall.

Gradient Descent

Optimization
Parameter Update Rule
ΞΈ ← ΞΈ βˆ’ Ξ± Β· βˆ‡L(ΞΈ)
Ξ± = learning rate Β· βˆ‡L(ΞΈ) = gradient of loss w.r.t. parameters
VariantBatch SizeTrade-off
Batch GDFull datasetStable but slow on large data
Stochastic GD (SGD)1 sampleNoisy but fast; can escape local minima
Mini-batch GD32–512Best of both β€” GPU-efficient
OptimizerKey Idea
MomentumAccumulate past gradients β€” faster convergence
RMSPropAdapt LR per parameter using moving avg of squared grads
AdamMomentum + RMSProp β€” default choice for most deep learning

Key ML Terminology

Glossary
TermMeaning
Feature (X)Input variable used for prediction
Label / Target (y)Output variable the model tries to predict
HyperparameterModel setting set before training (e.g. learning rate, depth)
Parameter (ΞΈ)Values learned during training (weights, biases)
EpochOne full pass through the entire training dataset
BatchSubset of training data used per gradient update
GeneralizationModel's ability to perform well on unseen data
Data leakageTest info inadvertently used in training β€” inflates metrics
Inductive biasAssumptions a model makes about the data (e.g. linearity)
CapacityModel's expressiveness / ability to fit complex functions

Encoding Categorical Variables

Preprocessing
EncodingHowWhen to Use
Label EncodingMap categories β†’ integers (0,1,2…)Ordinal variables; tree-based models
One-Hot EncodingBinary column per categoryNominal; linear/distance-based models
Ordinal EncodingMap in meaningful orderOrdinal with natural ranking
Target EncodingReplace category with mean targetHigh-cardinality categoricals
Binary / HashingHash to fixed-length binaryVery high-cardinality, speed critical
pandas β€” One-Hot Encoding
import pandas as pd
df = pd.get_dummies(df,
  columns=['color', 'city'],
  drop_first=True)
Dummy trap: Drop one category per feature (drop_first=True) to avoid perfect multicollinearity in linear models.

Foundational Principles

Theory
No Free Lunch (NFL) Theorem
No single algorithm is best for all problems
All algorithms perform equally averaged across all possible datasets β€” domain knowledge matters
Occam's Razor in ML
Prefer the simplest model that fits the data
Simpler models β†’ lower variance β†’ better generalization β€” complexity must be justified by gain
Universal Approximation Theorem
A neural network with 1 hidden layer can approximate any continuous function
Existence β‰  learnability β€” doesn't tell us how to find the weights
Practical takeaway: Always try a simple baseline (logistic regression, decision tree) before investing in complex models.

ML Basics Mastery Checklist

Self-Assessment

Core Concepts

Explain the difference between supervised, unsupervised, and reinforcement learning
Distinguish classification from regression with examples
Define features, labels, parameters, and hyperparameters
Explain bias–variance tradeoff and the error decomposition formula
Identify underfitting and overfitting from train/validation error patterns

Loss Functions

State and apply MSE and MAE for regression problems
State and apply Binary Cross-Entropy for classification
Choose the right loss function for a given task
Explain why log loss penalizes confident wrong predictions heavily

Data & Preprocessing

Split data correctly into train / validation / test sets
Implement k-fold cross-validation and explain why it reduces variance
Apply standardization and min-max normalization correctly
Fit scalers only on training data and transform test data
Encode categorical variables using one-hot or ordinal encoding appropriately
Handle imbalanced classes with SMOTE, class weights, or threshold tuning

Regularization

Explain L1 (Lasso) and L2 (Ridge) regularization and their effects
Tune the regularization strength Ξ» with cross-validation
Apply early stopping to prevent overfitting in iterative models

Optimization & Workflow

Describe gradient descent and the parameter update rule
Compare Batch, SGD, and Mini-batch gradient descent
Explain Adam optimizer and why it's the default in deep learning
Follow the complete ML workflow from problem definition to deployment
Tune hyperparameters with Grid Search or Random Search

Principles

State the No Free Lunch theorem and its practical implication
Apply Occam's Razor β€” start simple, add complexity only when justified
Detect and prevent data leakage in a pipeline
Choose appropriate evaluation metric for imbalanced classification

β–Ά Next Up: Sheet 2 β€” ML Algorithms

Linear Regression Β· Logistic Regression Β· Decision Trees Β· SVM Β· KNN Β· Naive Bayes Β· Ensemble Methods
ML Algorithms β†’
← Back