Guide To AI Logo
Unit 13

Classical Machine Learning Foundations

learning the core algorithms and concepts behind predictive modeling

SVM Maximum Margin Decision Boundary
Decision HyperplaneSV (Red Class)SV (Blue Class)← Margin →
Read diagram labels
  • Decision Hyperplane
  • Support vector: red class
  • Support vector: blue class
  • Maximum margin

Core Concepts Covered

  • Supervised vs. unsupervised vs. reinforcement learning
  • Linear & logistic regression, decision trees, and SVMs
  • Random forests and supervised model evaluation metrics
Local Setup Recommendation

To execute and experiment with the code cells below on your local machine, ensure you have set up your isolated virtual environments and scientific libraries by following the detailed protocols in Unit 03: Environment Setup or run them in Google Colab.

1. Taxonomy of Machine Learning

Machine Learning algorithms are broadly categorized based on the nature of the training data and feedback loops they receive:

Supervised Learning: The model is trained on labeled historical examples containing both features and explicit targets. If the target is a continuous real number (like predicting house prices), it is a Regression problem. If the target is a discrete label (like classifying an email as Spam or Inbox), it is a Classification problem.

Unsupervised Learning: The dataset contains no target labels, so the goal is to discover structure rather than predict a known target. Unit 14 develops this branch in depth through clustering, density estimation, dimensionality reduction, and pattern evaluation.

Reinforcement Learning: An autonomous agent learns optimal decision-making policies by taking actions within an environment to maximize a scalar feedback reward over time (such as training an autopilot or a game-playing engine).

2. Core Linear Models: Regression and Classification

Linear Regression: For features xx, weights ww, and intercept bb, the model predicts a continuous target with y^=wTx+b\hat{y}=w^Tx+b. A residual is the signed error e=yy^e=y-\hat{y}. Training commonly minimizes the Sum of Squared Errors (SSE), which makes large misses especially costly:

SSE=i=1n(yi(wTxi+b))2\text{SSE} = \sum_{i=1}^n (y_i - (w^T x_i + b))^2

For a one-feature house-price model y^=2x+10\hat{y}=2x+10, a home with x=3x=3 produces y^=16\hat{y}=16. If its observed price is y=18y=18, the residual is 1816=218-16=2 and this example contributes 22=42^2=4 to SSE. Linear regression is appropriate when the target is continuous and an approximately additive relationship is a useful baseline.

Logistic Regression: Binary logistic regression first computes a logit z=wTx+bz=w^Tx+b, then converts it into a class probability with the sigmoid function:

p(y=1x)=σ(z)=11+ezp(y=1\mid x)=\sigma(z)=\frac{1}{1+e^{-z}}

A threshold turns that probability into a label. With the common threshold 0.50.5, z=1.2z=1.2 gives σ(1.2)0.769\sigma(1.2)\approx0.769, so the predicted class is 11. Thresholds are decisions rather than fixed laws: a medical screener may lower its threshold to catch more possible cases, accepting more false alarms.

Training minimizes Binary Cross-Entropy, =[ylog(p)+(1y)log(1p)]\ell=-[y\log(p)+(1-y)\log(1-p)]. For the example above with y=1y=1 and p=0.769p=0.769, the loss is log(0.769)0.263-\log(0.769)\approx0.263. A confidently wrong probability receives a much larger penalty. Logistic regression is therefore a useful interpretable baseline for tasks such as spam detection or disease-risk classification.

One Example Each: Continuous Prediction and Class Probability

Linear Regressionŷ = 2x + 10observed y = 18predicted ŷ = 16residual = 2feature x = 3target yLogistic Regression0.5 thresholdsigmoid probabilityp ≈ 0.769class 1logit z = 1.2p(y=1)
Read diagram labels
  • Linear Regression
  • ŷ = 2x + 10
  • observed y = 18
  • predicted ŷ = 16
  • residual = 2
  • feature x = 3
  • target y
  • Logistic Regression
  • 0.5 threshold
  • sigmoid probability
  • p ≈ 0.769
  • class 1
  • logit z = 1.2
  • p(y=1)
Jupyter Code Notebook Cell
Python 3 (ipykernel)
In [1]:
# Practical implementation of Linear and Logistic regressions using Scikit-Learn
from sklearn.linear_model import LinearRegression, LogisticRegression
import numpy as np

# Linear Regression: Predict continuous outputs
X_reg = np.array([[1], [2], [3], [4]])
y_reg = np.array([2.1, 3.9, 6.1, 8.0])

reg_model = LinearRegression().fit(X_reg, y_reg)
print("Linear Regression Slope (w):", reg_model.coef_[0].round(2))
print("Linear Regression Intercept (b):", reg_model.intercept_.round(2))

# Logistic Regression: Classify binary categories
X_clf = np.array([[1], [2], [5], [6]])
y_clf = np.array([0, 0, 1, 1])

clf_model = LogisticRegression().fit(X_clf, y_clf)
print("Logistic Prediction for x=1.5 (Class):", clf_model.predict([[1.5]])[0])
print("Logistic Probabilities for x=3.5 (P(0), P(1)):", clf_model.predict_proba([[3.5]])[0].round(2))
Out [1]:
Linear Regression Slope (w): 1.98
Linear Regression Intercept (b): 0.08
Logistic Prediction for x=1.5 (Class): 0
Logistic Probabilities for x=3.5 (P(0), P(1)): [0.5 0.5]

3. Non-Linear Supervised Models: SVMs, Decision Trees, and Random Forests

Supervised learning is not limited to one straight regression line. SVMs can build maximum-margin boundaries, while trees and forests learn conditional rules and feature interactions.

Support Vector Machines (SVMs): A linear SVM predicts from the sign of wTx+bw^Tx+b and chooses the separating hyperplane that maximizes the margin. The closest training examples are the support vectors; they anchor the solution, while moving a point far from the boundary usually has no effect. In the canonical scaling, the distance between the two supporting hyperplanes is 2/w2/\lVert w\rVert, so minimizing w\lVert w\rVert produces a wider margin.

The perpendicular distance from a point xx to a boundary wTx+b=0w^Tx+b=0 is wTx+b/w|w^Tx+b|/\lVert w\rVert. For 2x1x2+1=02x_1-x_2+1=0 and x=(1,1)x=(1,1), the distance is 2(1)1+1/22+(1)2=2/50.894|2(1)-1+1|/\sqrt{2^2+(-1)^2}=2/\sqrt{5}\approx0.894. This geometry is why unscaled features can distort an SVM boundary.

Hard and Soft Margins: A hard-margin SVM requires every training point to be correctly separated and works only when the classes are linearly separable. A soft-margin SVM introduces slack variables that permit points to enter the margin or be misclassified. The CC hyperparameter prices those violations: large CC favors fewer training errors and a potentially narrower boundary; small CC accepts more violations to obtain stronger regularization and a wider margin.

The Kernel Trick (Intuitive Analogy): Imagine drawing a circle of red dots on a sheet of paper, surrounded by a larger ring of blue dots. You cannot draw a straight line on that 2D paper to separate them. However, what if you 'pop' the center of the paper upward, pushing the red dots into 3D space? You can now pass a flat 2D sheet of glass (a linear hyperplane) horizontally between the floating red dots and the flat blue dots. The Kernel Trick measures similarities as if points had been mapped into that richer space, without explicitly calculating every high-dimensional coordinate. The radial-basis-function (RBF) kernel is a common choice; its γ\gamma setting controls how local each point's influence is.

With an RBF kernel, a small γ\gamma gives each example broad influence and tends to create a smoother boundary; a large γ\gamma makes influence highly local and can produce a complicated boundary that overfits. Tune CC and γ\gamma together using validation data. Put scaling inside a pipeline so it learns only from training data. SVMs are especially useful for small-to-medium, high-dimensional datasets such as text or biological measurements, but kernel training can become costly on very large datasets.

Decision Trees: A tree recursively asks threshold questions such as age <= 30 and chooses splits that make the child nodes purer. For a parent with 66 positive and 44 negative examples, the Gini impurity is 10.620.42=0.481-0.6^2-0.4^2=0.48. Suppose a candidate split creates a pure four-example left node and a right node with 22 positive and 44 negative examples. The right-node impurity is 1(2/6)2(4/6)2=4/91-(2/6)^2-(4/6)^2=4/9, so the weighted child impurity is (4/10)(0)+(6/10)(4/9)0.267(4/10)(0)+(6/10)(4/9)\approx0.267. The Gini reduction is 0.480.267=0.2130.48-0.267=0.213, which the tree compares with other candidate splits.

Trees naturally model non-linear interactions and can classify loan risk or regress a home's price, but an unrestricted tree can memorize noise. Depth limits, minimum leaf sizes, and pruning control this variance. Entropy and information gain provide an alternative split criterion; Unit 12 develops their information-theory foundations.

Random Forests: A forest trains many trees on different bootstrap samples, created by sampling the training rows with replacement. Each split also considers only a random subset of features, preventing the same dominant predictor from making every tree alike. For classification, trees vote; for regression, their numeric predictions are averaged. If five fraud-classification trees vote [1,1,0,1,0][1,1,0,1,0], the forest predicts class 11 by a 33-to-22 majority. Combining diverse, imperfect trees cancels some of their individual fluctuations, reducing variance and usually generalizing better than one deep tree.

Jupyter Code Notebook Cell
Python 3 (ipykernel)
In [1]:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

# Load a binary classification dataset and keep a held-out test set.
dataset = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
    dataset.data,
    dataset.target,
    test_size=0.25,
    stratify=dataset.target,
    random_state=7,
)

# Scaling is part of the pipeline, so it is fitted only on training data.
svm_model = make_pipeline(
    StandardScaler(),
    SVC(kernel="rbf", C=1.0, gamma="scale"),
)
svm_model.fit(X_train, y_train)

print("SVM test accuracy:", round(svm_model.score(X_test, y_test), 3))
print("Support vectors per class:", svm_model.named_steps["svc"].n_support_)
Out [1]:
SVM test accuracy: 0.972
Support vectors per class: [51 56]

4. Classification Metrics and Model Evaluation

To evaluate our models, we construct a Confusion Matrix tracking True Positives (TPTP), False Positives (FPFP), True Negatives (TNTN), and False Negatives (FNFN). From these, we calculate crucial evaluation metrics:

Accuracy: Overall proportion of correct predictions: TP+TNTP+FP+TN+FN\frac{TP+TN}{TP+FP+TN+FN}.

Precision: Out of all positive predictions, how many were actually positive? Highly critical when false positives are expensive (e.g., spam filters): Precision=TPTP+FP\text{Precision} = \frac{TP}{TP + FP}

Recall (Sensitivity): Out of all actual positive samples, how many did the model find? Highly critical when false negatives are dangerous (e.g., medical diagnoses): Recall=TPTP+FN\text{Recall} = \frac{TP}{TP + FN}

Specificity: Out of all actual negative samples, how many did the model correctly reject? Specificity=TNTN+FP\text{Specificity}=\frac{TN}{TN+FP}.

F1F_1-Score: The harmonic mean of Precision and Recall, providing a robust evaluation metric for highly imbalanced datasets: F1=2PrecisionRecallPrecision+RecallF_1 = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}}

For TP=40TP=40, FP=10FP=10, TN=45TN=45, and FN=5FN=5, there are 100100 cases. Accuracy is (40+45)/100=85%(40+45)/100=85\%, precision is 40/50=80%40/50=80\%, recall is 40/4588.9%40/45\approx88.9\%, specificity is 45/5581.8%45/55\approx81.8\%, and F1=2TP/(2TP+FP+FN)=80/9584.2%F_1=2TP/(2TP+FP+FN)=80/95\approx84.2\%. One confusion matrix therefore reveals several different views of the same predictions.

A ROC curve varies the classification threshold and plots the true-positive rate against the false-positive rate. ROC-AUC summarizes how well a model ranks a randomly chosen positive above a randomly chosen negative across all thresholds. It is useful when comparing ranking performance before selecting an operating threshold, but it does not encode the application's actual error costs; for rare positive classes, also inspect precision-recall behavior.

Choose the final threshold and metric based on the cost of errors. In a screening task, missing a true positive can be dangerous, so recall may matter more than raw accuracy. Always calculate final metrics on a held-out test set that was not used to fit the model, tune hyperparameters, or select the threshold.

Jupyter Code Notebook Cell
Python 3 (ipykernel)
In [1]:
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

dataset = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
    dataset.data,
    dataset.target,
    test_size=0.25,
    stratify=dataset.target,
    random_state=7,
)

model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1_000))
model.fit(X_train, y_train)
predictions = model.predict(X_test)

print("Test accuracy:", round(accuracy_score(y_test, predictions), 3))
print("Recall for malignant cases:", round(recall_score(y_test, predictions, pos_label=0), 3))
Out [1]:
Test accuracy: 0.979
Recall for malignant cases: 0.981

Hands-On Kaggle Challenge #1

Titanic: Machine Learning from Disaster

The most famous starter classification challenge on Kaggle! Predict survival outcomes on the Titanic using classification models (like Support Vector Machines, Logistic Regression, or Decision Trees) and submit your predictions to get ranked on the live leaderboard.

Refer back to Unit 03 for environment and Colab setup!
Join Kaggle Challenge

Hands-On Kaggle Challenge #2

House Prices: Advanced Regression Techniques

The classic starter regression challenge! Predict sales prices of residential houses using advanced regressions and tree-based ensembles (like Random Forests or Gradient Boosting) and submit your predictions.

Refer back to Unit 03 for environment and Colab setup!
Join Kaggle Challenge

Interactive Practice Quiz

Test your understanding with instant feedback

QUESTION 01

Which of the following describes the mathematical output range of the Sigmoid activation function σ(z)=11+ez\sigma(z) = \frac{1}{1 + e^{-z}}?

QUESTION 02

If a cancer diagnostic model must minimize the danger of missing actual positive cancer cases (False Negatives), which metric should we prioritize maximizing?

QUESTION 03

A logistic regression model produces a logit of z=1.2z=1.2. Using σ(1.2)0.769\sigma(1.2)\approx0.769 and a threshold of 0.50.5, what does the model predict?

QUESTION 04

What is the primary role of the Support Vector Machine (SVM) algorithm?

QUESTION 05

Compute the F1F_1-Score for a classification model that achieves a Precision of 0.800.80 and a Recall of 0.800.80:

QUESTION 06

What is the core mathematical purpose of the 'Kernel Trick' inside Support Vector Machines?

QUESTION 07

How do Decision Trees choose split points during training?

QUESTION 08

What is the core mechanism of the Random Forest ensemble model?

QUESTION 09

A classifier has TP=40TP=40, FP=10FP=10, TN=45TN=45, and FN=5FN=5. What is its specificity?

QUESTION 10

The loss function minimized by standard Linear Regression is called: