Supervised Learning Guide
Supervised Learning Guide
Supervised Learning
A Detailed Guide to Regression & Classification Algorithms
REGRESSION CLASSIFICATION
0 Foundations of Supervised
Learning
The shared vocabulary you need before reading any algorithm chapter
Supervised learning is the branch of machine learning where a model learns from
labelled examples. You hand the algorithm a set of input–output pairs, and it
searches for a function that maps inputs to outputs well enough to generalise to
data it has never seen.
The two families of problems differ only in the nature of the target:
Because low training error is easy to fake by memorising, we always split the data. A
typical workflow holds out a test set that the model never sees during training, and often a
validation set (or cross-validation) for tuning hyperparameters. Performance on held-out
data is the only honest estimate of how the model will behave in production.
3
FOUNDATIONS SUPERVISED LEARNING · DETAILED GUIDE
memorises noise. Lowering one usually raises the other; the art is finding the sweet spot.
• Underfitting shows up as high error on both training and test data. The fix is a more
flexible model or better features.
• Overfitting shows up as low training error but high test error. The fix is more data,
regularisation, or a simpler model.
Of predicted positives, how many are truly False positives are expensive (e.g.
Precision
positive. spam filters).
4
FOUNDATIONS SUPERVISED LEARNING · DETAILED GUIDE
Well-calibrated probabilities
Log loss Penalises confident wrong probabilities.
matter.
5
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
PART I
Regression
Predicting a continuous number — from the straight-line
baseline to the boosted-tree champion.
1 Linear Regression
2 Ridge Regression
3 Lasso Regression
4 Elastic Net
5 Decision Tree Regressor
6 Random Forest Regressor
7 Gradient Boosting / XGBoost
6
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
1 Linear Regression
The straight-line baseline every regression model is measured against
Linear regression is the foundation of the entire family. It models the target as a
weighted sum of the features plus an intercept, then chooses the weights that make
the squared prediction errors as small as possible.
Intuition
Imagine a cloud of points and you want the single straight line that passes through them as
snugly as possible. With more than one feature the line becomes a flat plane or hyperplane,
but the idea is unchanged: find the slope(s) and intercept that minimise the total squared
vertical distance between the line and the points.
How it works
The model assumes the prediction is linear in the parameters:
Training minimises the residual sum of squares, equivalently the mean squared error,
over the m training examples. This loss is called Ordinary Least Squares (OLS):
Because the loss is convex and quadratic, there is a unique optimum. It can be found in one
step with the normal equation, or iteratively with gradient descent for very large
datasets:
Key assumptions
• Linearity — the relationship between features and target is genuinely linear.
• Independence of errors and homoscedasticity (constant error variance).
• Little multicollinearity — features are not near-duplicates of each other.
• Roughly normal residuals if you want valid confidence intervals and p-values.
Hyperparameters
7
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ Fast, closed-form solution and trivial to ▸ Can only capture linear relationships.
train. ▸ Sensitive to outliers because errors are
▸ Highly interpretable — each coefficient is a squared.
direct effect size. ▸ Unstable coefficients under
▸ Strong, well-understood statistical theory. multicollinearity.
▸ A natural baseline for any regression task. ▸ Underfits complex, non-linear data.
When to use it
Reach for linear regression as your first baseline, when interpretability matters more than
raw accuracy, or when the relationship really is approximately linear and you have more
rows than features.
model = LinearRegression()
[Link](X_train, y_train)
print(model.coef_, model.intercept_)
print('R2:', [Link](X_test, y_test))
8
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
2 Ridge Regression
Linear regression + L2 penalty for stability under correlated features
Ridge regression is linear regression with an L2 penalty. It keeps every feature but
shrinks the coefficients toward zero, trading a little bias for a large reduction in
variance — especially valuable when features are correlated.
Intuition
When predictors are correlated, OLS can assign wildly large, oscillating coefficients that fit
noise. Ridge adds a cost for large coefficients, so the optimiser prefers small, stable
weights. The result is a model that generalises better even though it fits the training data
slightly worse.
How it works
Ridge adds the squared L2 norm of the coefficients (excluding the intercept) to the OLS
loss, scaled by a strength α (often written λ):
It still has a closed-form solution, and the added αI term guarantees the matrix is always
invertible — curing the instability of pure OLS:
The effect of α
At α = 0 Ridge is identical to OLS. As α grows, all coefficients shrink smoothly toward (but
never exactly to) zero, biasing the model and reducing variance. You tune α with
cross-validation; RidgeCV does this automatically. Always scale features first, since the
penalty is sensitive to their magnitudes.
Hyperparameters
Hyperparameter What it controls
9
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ Tames multicollinearity and stabilises ▸ Never sets coefficients exactly to zero —
coefficients. no feature selection.
▸ Reduces overfitting via a single, intuitive ▸ Keeps all features, so the model stays
knob. dense and less interpretable.
▸ Retains the closed-form, fast solution of ▸ Requires feature scaling to behave
OLS. sensibly.
▸ Works well when many features each ▸ Still fundamentally a linear model.
contribute a little.
When to use it
Use Ridge when you have many correlated features that you believe are all relevant, when
OLS coefficients look unstable, or whenever you want a gentle, reliable reduction in
overfitting without dropping any predictors.
model = make_pipeline(
StandardScaler(),
RidgeCV(alphas=[0.1, 1.0, 10.0, 100.0]) # picks best alpha by CV
)
[Link](X_train, y_train)
print('R2:', [Link](X_test, y_test))
10
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
3 Lasso Regression
Linear regression + L1 penalty that performs automatic feature selection
Lasso regression swaps Ridge's squared penalty for an absolute-value (L1) penalty.
That single change lets it drive some coefficients exactly to zero, performing
automatic feature selection.
Intuition
The L1 penalty has sharp corners on the coefficient axes. Geometrically, the optimum
tends to land on those corners, where one or more coefficients are exactly zero. The
practical upshot: Lasso produces sparse models that use only a subset of the features,
which is invaluable when you suspect many features are irrelevant.
How it works
Lasso minimises the OLS loss plus the L1 norm of the coefficients:
Because the absolute value is not differentiable at zero, there is no closed form. scikit-learn
solves it with coordinate descent, optimising one coefficient at a time while holding the
others fixed and repeating until convergence.
Hyperparameters
Hyperparameter What it controls
11
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ Built-in feature selection — yields sparse, ▸ With correlated features it arbitrarily keeps
interpretable models. one and zeros the rest.
▸ Excellent when only a few features truly ▸ Can be unstable: small data changes flip
matter. which features survive.
▸ Reduces overfitting and model size at ▸ No closed form; slower to fit than Ridge.
once. ▸ May discard useful features if α is too
▸ LassoCV tunes α automatically. aggressive.
When to use it
Reach for Lasso in high-dimensional settings where you expect many features to be useless
and want the model to tell you which ones, or whenever a compact, interpretable set of
predictors is the goal.
lasso = model.named_steps['lassocv']
print('best alpha:', lasso.alpha_)
print('features kept:', (lasso.coef_ != 0).sum())
12
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
4 Elastic Net
A tunable blend of Lasso and Ridge — sparsity with stability
Elastic Net blends the L1 and L2 penalties, combining Lasso's feature selection with
Ridge's stability. It is the default choice when you have many correlated features
and still want a sparse model.
Intuition
Lasso struggles with groups of correlated features — it picks one and discards the rest,
almost at random. Ridge keeps the whole group but never zeros anything. Elastic Net takes
the best of both: the L1 part still removes irrelevant features, while the L2 part encourages
correlated features to be selected (or dropped) together as a group.
How it works
The loss mixes both penalties, with a ratio that decides how much of each:
Here α sets the overall regularisation strength and ρ (scikit-learn's l1_ratio) sets the
balance: ρ = 1 is pure Lasso, ρ = 0 is pure Ridge, and values in between blend the two.
Hyperparameters
Hyperparameter What it controls
13
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ Combines feature selection (L1) with ▸ Two hyperparameters to tune instead of
stability (L2). one.
▸ Handles groups of correlated features ▸ Still a linear model — cannot capture
gracefully. non-linearity.
▸ Usually the safest regularised-linear ▸ Slightly less interpretable than pure Lasso.
default. ▸ Requires feature scaling.
▸ ElasticNetCV tunes both α and l1_ratio
together.
When to use it
Choose Elastic Net when you have high-dimensional data with correlated features and want
both sparsity and stability — it is often the best-performing linear model in practice and a
sensible default over plain Lasso.
model = make_pipeline(
StandardScaler(),
ElasticNetCV(l1_ratio=[0.1, 0.5, 0.7, 0.9, 1.0], cv=5)
)
[Link](X_train, y_train)
14
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
A decision tree regressor splits the feature space into rectangular regions with a
series of yes/no questions, then predicts the average target value within each
region. It captures non-linear relationships with zero assumptions about their shape.
Intuition
Think of a flowchart of questions: Is square footage > 1500? If yes, is the house newer than
1990? Each answer narrows the data down. The leaves at the bottom hold groups of similar
training points, and the prediction for any new point is simply the mean target of the leaf it
lands in.
How it works
The tree is grown greedily. At each node it searches every feature and every possible
threshold to find the split that most reduces the impurity — for regression, the variance
(mean squared error) of the target within the child nodes:
Splitting continues recursively until a stopping rule fires (maximum depth reached, too few
samples to split, or no split improves the loss). Without limits, a tree will grow until each
leaf is nearly pure — which means it memorises the training set.
Hyperparameters
Hyperparameter What it controls
15
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ Captures non-linear patterns and ▸ High variance — prone to overfitting
interactions automatically. without pruning.
▸ Needs no feature scaling and handles ▸ Predictions are piecewise-constant
mixed data types. (blocky), not smooth.
▸ Highly interpretable — you can read the ▸ Small data changes can produce a very
rules directly. different tree.
▸ Robust to outliers and irrelevant features. ▸ A single tree rarely matches ensemble
accuracy.
When to use it
Use a single tree when interpretability is paramount and you can show the rules to
stakeholders, or as a building block and intuition pump before moving to Random Forests
and Gradient Boosting, which almost always predict better.
model = DecisionTreeRegressor(
max_depth=5,
min_samples_leaf=10,
random_state=42
)
[Link](X_train, y_train)
print('R2:', [Link](X_test, y_test))
16
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
Intuition
One tree is a noisy expert. A forest is a committee of hundreds of decorrelated experts:
each makes its own errors, but when you average their votes the errors cancel and the
signal remains. This is the wisdom-of-crowds principle applied to trees.
How it works
Two sources of randomness make the trees different from each other:
For regression, the final prediction is the average over all trees:
Hyperparameters
Hyperparameter What it controls
Depth limit per tree; forests tolerate deep trees better than a lone
max_depth
tree.
17
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ Strong accuracy out of the box with little ▸ A black box compared with a single tree.
tuning. ▸ Large models are memory-heavy and
▸ Resists overfitting thanks to averaging. slower to predict.
▸ Handles non-linearity, interactions, and ▸ Can't extrapolate beyond the range seen in
mixed types. training.
▸ Provides feature-importance scores and ▸ Often edged out on accuracy by tuned
OOB estimates. gradient boosting.
▸ Parallelises trivially across cores.
When to use it
Random forest is the dependable workhorse: an excellent default when you want strong
accuracy with minimal tuning, robust behaviour on messy tabular data, and useful feature
importances — all without worrying much about scaling or hyperparameters.
model = RandomForestRegressor(
n_estimators=300,
max_features='sqrt',
min_samples_leaf=2,
oob_score=True,
n_jobs=-1, random_state=42
)
[Link](X_train, y_train)
print('OOB R2:', model.oob_score_)
18
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
Gradient boosting builds an ensemble of trees sequentially, where each new tree
is trained to correct the errors of the trees before it. XGBoost, LightGBM and
CatBoost are highly optimised, regularised implementations of this idea — and they
dominate tabular-data competitions.
Intuition
Where a random forest builds many independent trees in parallel and averages them,
boosting builds trees one after another. Each tree focuses on the mistakes still left by the
running ensemble. Add enough small corrective trees, each scaled down by a learning rate,
and the model gradually converges on the target — turning many weak learners into one
strong learner.
How it works
The model is an additive sum of trees. Starting from a constant prediction, each stage fits a
new tree to the negative gradient of the loss (for squared error, this is simply the residuals)
and adds a shrunken version of it:
The learning rate ν (often 0.01–0.3) shrinks each tree's contribution. Smaller rates need
more trees but generalise better. The interplay between learning rate and number of trees
is the heart of tuning a boosted model.
Hyperparameters
Hyperparameter What it controls
learning_rate Shrinkage per tree; lower is more accurate but needs more trees.
19
REGRESSION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ State-of-the-art accuracy on structured / ▸ Many interacting hyperparameters —
tabular data. needs careful tuning.
▸ Captures complex non-linear interactions. ▸ Sequential training is slower and harder to
▸ Handles missing values and gives feature parallelise than forests.
importances. ▸ Easy to overfit if learning rate / trees are
▸ Early stopping and regularisation control mis-set.
overfitting well. ▸ Less interpretable; effectively a black box.
When to use it
Use gradient boosting when accuracy on tabular data is the priority and you are willing to
tune. It is the go-to choice for Kaggle-style problems, ranking, and most high-stakes
structured-data prediction — with early stopping to find the right number of trees
automatically.
model = XGBRegressor(
n_estimators=2000, learning_rate=0.03,
max_depth=4, subsample=0.8, colsample_bytree=0.8,
reg_lambda=1.0, early_stopping_rounds=50, random_state=42
)
[Link](X_train, y_train,
eval_set=[(X_test, y_test)], verbose=False)
20
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
PART II
Classification
Predicting a category — from interpretable linear models
to margins, neighbours, and ensembles.
1 Logistic Regression
2 Decision Tree Classifier
3 Random Forest Classifier
4 XGBoost / LightGBM / CatBoost
5 Support Vector Machine (SVM)
6 Naive Bayes
7 K-Nearest Neighbours (KNN)
21
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
1 Logistic Regression
A linear model squashed into probabilities — the classification baseline
Intuition
Linear regression can output any number, which is useless for a probability that must live
between 0 and 1. Logistic regression fixes this by squashing the linear output through the
sigmoid, producing a clean probability. You then threshold that probability (typically at 0.5)
to decide the class.
How it works
First compute a linear score, then squash it with the sigmoid to get a probability:
The model is trained by minimising log loss (binary cross-entropy), which heavily penalises
confident wrong predictions:
This loss is convex but has no closed form, so it is solved with gradient descent or
specialised solvers. The decision boundary is linear: the model separates classes with a
straight line, plane, or hyperplane. For more than two classes it generalises to the softmax
(multinomial) form.
Regularisation is built in
scikit-learn's LogisticRegression applies L2 regularisation by default, controlled by C —
the inverse of strength, so smaller C means stronger regularisation. You can switch to L1
for sparsity or Elastic Net. Scaling features helps the solver converge.
Hyperparameters
Hyperparameter What it controls
solver Optimiser (lbfgs, liblinear, saga); some pair with specific penalties.
22
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ Outputs calibrated probabilities, not just ▸ Decision boundary is linear — misses
labels. complex patterns.
▸ Fast, simple, and highly interpretable ▸ Needs feature engineering to model
(coefficients = log-odds). non-linear effects.
▸ Strong, hard-to-beat baseline for ▸ Sensitive to outliers and strong
classification. multicollinearity.
▸ Regularisation guards against overfitting. ▸ Assumes a roughly linear relationship in
the log-odds.
When to use it
Use logistic regression as your first classification baseline, whenever you need
interpretable probabilities (credit scoring, medical risk), or when the classes are close to
linearly separable. It is fast enough to train on very large datasets.
model = make_pipeline(
StandardScaler(),
LogisticRegression(C=1.0, class_weight='balanced', max_iter=1000)
)
[Link](X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
23
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
The classification tree works exactly like its regression cousin, but instead of
predicting an average it predicts the majority class of each leaf and chooses splits
that make the leaves as pure as possible.
Intuition
Ask a sequence of yes/no questions that progressively sort examples into groups
dominated by a single class. A new example follows the questions down to a leaf and is
assigned that leaf's majority class — or the class proportions as probabilities.
How it works
At each node the tree picks the split that most reduces impurity. The two common
impurity measures for classification are Gini and entropy:
Here pk is the fraction of class k in the node. A node with one class has impurity 0; a 50/50
mix is maximally impure. The tree greedily chooses the split giving the largest weighted
drop in impurity (the information gain), then recurses.
Gini or entropy?
In practice the two give very similar trees. Gini is slightly faster to compute and is
scikit-learn's default; entropy comes from information theory. Don't agonise over the
choice — depth and leaf-size limits matter far more for performance.
Hyperparameters
Hyperparameter What it controls
24
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ Easy to visualise and explain to ▸ Overfits readily without depth or leaf limits.
non-experts. ▸ Unstable — small data changes reshape
▸ Handles non-linear boundaries and feature the tree.
interactions. ▸ Biased toward features with many levels.
▸ No scaling needed; works with mixed ▸ A single tree usually trails ensembles in
feature types. accuracy.
▸ Naturally provides class probabilities.
When to use it
Use a single classification tree when transparency is the priority and you must justify each
decision, for quick exploratory insight into which features drive the outcome, or as the
conceptual stepping stone to forests and boosting.
model = DecisionTreeClassifier(
criterion='gini', max_depth=5,
min_samples_leaf=10, class_weight='balanced',
random_state=42
)
[Link](X_train, y_train)
25
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
A random forest classifier trains many decorrelated decision trees and lets them
vote. The majority class wins, and averaging the trees' probabilities gives smooth,
reliable predictions with strong out-of-the-box accuracy.
Intuition
Each individual tree is an overconfident, noisy classifier. Train hundreds of them on
different bootstrap samples and feature subsets, and their idiosyncratic mistakes cancel
when you take a vote. The forest is dramatically more stable and accurate than any single
tree.
How it works
The mechanics mirror the regression forest — bagging plus random feature selection at
each split — but aggregation differs. For a class label the forest takes a majority vote; for
probabilities it averages each tree's class proportions:
Hyperparameters
Hyperparameter What it controls
max_features Features per split (default √n); the key decorrelation knob.
26
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ High accuracy with minimal tuning — a ▸ Less interpretable than a single tree.
superb default. ▸ Memory- and compute-heavy at prediction
▸ Resists overfitting through averaging. time.
▸ Robust to outliers, noise, and irrelevant ▸ Can be biased on highly imbalanced data
features. without weighting.
▸ Gives feature importances and OOB error ▸ Frequently out-predicted by tuned gradient
estimates. boosting.
▸ Handles many classes and large feature
sets.
When to use it
Random forest is the reliable first choice for most tabular classification tasks: it delivers
strong accuracy with almost no tuning, tolerates messy data, and surfaces feature
importances — ideal when you need a solid model fast.
model = RandomForestClassifier(
n_estimators=400, max_features='sqrt',
class_weight='balanced', oob_score=True,
n_jobs=-1, random_state=42
)
[Link](X_train, y_train)
print('OOB accuracy:', model.oob_score_)
27
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
For classification, gradient-boosted trees optimise log loss instead of squared error,
but the engine is identical: trees added one at a time, each correcting the
ensemble's current errors. XGBoost, LightGBM and CatBoost are the dominant
tabular classifiers.
Intuition
Start with a constant guess at the class probabilities, then repeatedly add small trees that
push the predicted probabilities toward the truth. Each tree fits the gradient of the log-loss
— effectively the residual error in probability space — and a learning rate keeps each
correction modest so the model converges smoothly.
How it works
The additive update is the same as in regression, only the loss changes to log loss. The raw
additive output is a log-odds score, converted to a probability by the sigmoid (or softmax
for multi-class):
Hyperparameters
Hyperparameter What it controls
max_depth / num_leaves Tree complexity (depth for XGBoost, leaves for LightGBM).
28
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ Best-in-class accuracy on structured / ▸ Many hyperparameters; tuning takes
tabular data. effort.
▸ Models complex non-linear interactions ▸ Sequential training is slower than a forest.
automatically. ▸ Overfits if learning rate / depth are mis-set.
▸ Handles missing values and imbalance ▸ Low interpretability without tools like
well. SHAP.
▸ Early stopping and regularisation control
overfitting.
When to use it
Use boosted trees when classification accuracy on tabular data is what matters most and
you can invest in tuning. They win the majority of structured-data competitions and excel
at fraud detection, churn, ranking, and risk scoring.
model = XGBClassifier(
n_estimators=2000, learning_rate=0.03, max_depth=4,
subsample=0.8, colsample_bytree=0.8,
eval_metric='logloss', early_stopping_rounds=50,
random_state=42
)
[Link](X_train, y_train,
eval_set=[(X_test, y_test)], verbose=False)
29
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
A Support Vector Machine finds the decision boundary that separates the classes
with the widest possible margin. With the kernel trick it can draw highly
non-linear boundaries while still solving a clean, convex optimisation.
Intuition
Many lines can separate two classes, but SVM picks the one that sits as far as possible from
the nearest points of either class. Those nearest points are the support vectors — they
alone define the boundary. A wide margin means the model is confident and tends to
generalise well.
How it works
SVM maximises the margin, which is equivalent to minimising the norm of the weight
vector subject to classifying points correctly. A slack term (controlled by C) allows some
violations for non-separable data, giving the soft-margin formulation:
The second term is the hinge loss. For non-linear problems the kernel trick implicitly
maps data into a higher-dimensional space where it becomes separable, using a kernel
function such as the RBF (Gaussian) kernel — without ever computing the mapping
explicitly:
Hyperparameters
Hyperparameter What it controls
30
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ Effective in high-dimensional spaces, even ▸ Scales poorly — slow on large datasets
when features > samples. (roughly O(m²–m³)).
▸ Kernel trick captures complex non-linear ▸ Sensitive to C, gamma, and kernel choice;
boundaries. needs tuning.
▸ Margin maximisation gives good ▸ Requires feature scaling to work properly.
generalisation. ▸ Probabilities are not native (need extra
▸ Only support vectors matter — calibration).
memory-efficient model.
When to use it
SVMs shine on small-to-medium datasets with clear margins, especially high-dimensional
ones like text classification or bioinformatics. A linear SVM is a strong, fast choice for sparse
high-dimensional data; the RBF kernel handles non-linear problems when you have the
time to tune.
model = make_pipeline(
StandardScaler(),
SVC(kernel='rbf', C=1.0, gamma='scale',
class_weight='balanced', probability=True)
)
[Link](X_train, y_train)
31
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
6 Naive Bayes
Bayes' theorem plus a bold independence assumption — fast and
surprisingly good
Naive Bayes is a probabilistic classifier built directly on Bayes' theorem, with one
bold simplifying assumption: that all features are conditionally independent given
the class. That 'naive' assumption is rarely true, yet the method works remarkably
well.
Intuition
For a new example, ask: given these feature values, which class is most probable? Bayes'
theorem lets you flip that into quantities you can estimate from training data — how likely
each feature value is within each class. Multiply those likelihoods together with the class's
base rate, and the largest product wins.
How it works
Bayes' theorem says the posterior probability of a class is proportional to the prior times
the likelihood. The naive independence assumption lets the joint likelihood factor into a
simple product over features:
Each P(xj | y) is estimated from the training data; the form depends on the feature type,
which gives the three common variants. Probabilities are multiplied in log-space to avoid
numerical underflow, and Laplace smoothing handles unseen values.
Hyperparameters
Hyperparameter What it controls
fit_prior Whether to learn class priors from data or assume them uniform.
32
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ Extremely fast to train and predict, even ▸ The independence assumption is usually
on huge data. false.
▸ Works well with very high-dimensional ▸ Probability estimates are poorly calibrated.
data (e.g. text). ▸ Correlated features can degrade accuracy.
▸ Needs little training data to estimate ▸ Generally less accurate than discriminative
parameters. models when data is plentiful.
▸ Simple, with no real tuning required.
When to use it
Naive Bayes is the classic choice for text classification — spam filtering, sentiment,
document categorisation — and any high-dimensional, sparse problem where speed
matters and a strong, cheap baseline is welcome.
model = make_pipeline(
TfidfVectorizer(),
MultinomialNB(alpha=1.0)
)
[Link](text_train, y_train)
33
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
7 K-Nearest Neighbours
Lazy, instance-based voting by the closest examples
K-Nearest Neighbours is the simplest classifier of all: to label a new point, find the k
closest training points and let them vote. It does no real training — it just memorises
the data and defers all work to prediction time.
Intuition
Things that are close together tend to be alike. To classify a new example, look at its k
nearest neighbours in feature space and assign whichever class is most common among
them. There is no model to fit — the training data is the model, which is why KNN is called a
lazy or instance-based learner.
How it works
Pick a value of k and a distance metric (Euclidean is standard). For a query point, compute
its distance to every training point, take the k smallest, and predict the majority class
among them — optionally weighting closer neighbours more heavily:
Hyperparameters
Hyperparameter What it controls
n_neighbors The k — how many neighbours vote. The central tuning parameter.
34
CLASSIFICATION ALGORITHMS SUPERVISED LEARNING · DETAILED GUIDE
✓ Strengths ✗ Limitations
▸ Dead simple and intuitive, with no training ▸ Prediction is slow — it scans all data each
phase. time.
▸ Naturally handles non-linear, multi-class ▸ Suffers badly from the curse of
boundaries. dimensionality.
▸ Makes no assumptions about the data ▸ Mandatory feature scaling; sensitive to
distribution. irrelevant features.
▸ Adapts instantly as new data is added. ▸ Memory-hungry: the whole training set
must be stored.
When to use it
KNN suits small, low-dimensional datasets with meaningful distances, as a quick baseline,
or for recommendation-style 'find similar items' tasks. Avoid it on large or high-dimensional
data, where prediction becomes slow and distances lose meaning.
model = make_pipeline(
StandardScaler(),
KNeighborsClassifier(n_neighbors=7, weights='distance')
)
[Link](X_train, y_train)
35
CHEAT-SHEET SUPERVISED LEARNING · DETAILED GUIDE
Use these tables as a fast lookup once you know the algorithms. The golden rule of
applied machine learning still holds: start simple, establish a baseline, and only add
complexity when the data justifies it.
Linear + penalty that zeros weak You want automatic feature selection
Lasso (L1)
coefficients. and a sparse model.
Sequential trees minimising log You want top accuracy and can invest
Boosted Trees
loss. in tuning.
36
CHEAT-SHEET SUPERVISED LEARNING · DETAILED GUIDE
A closing thought
No algorithm is universally best — this is the famous no free lunch theorem. The right
choice depends on your data size, dimensionality, the importance of interpretability, and
how much accuracy is worth to you. Understanding the trade-offs in this guide is what lets
you make that call quickly and well.
37