Module Material: 04. AI & Machine Learning Foundations

Source presentation: DA06-07 AI-ML-Intro.pdf

Lecture 04: Artificial Intelligence & Machine Learning Foundations

Course: Introduction to Data Analytics (CE KMITL)
Source Material: DA06-07 AI-ML-Intro.pdf (140 slides)
Key Topics: AI vs ML vs DL hierarchy, Supervised vs Unsupervised learning, Model formulations, Regression evaluation metrics (MAE, MSE, RMSE, MAPE, R2R^2), Classification evaluation intro (Confusion Matrix, Accuracy), End-to-end ML workflow, Linear Regression derivation, Decision Trees, Logistic Regression, Naive Bayes, K-Nearest Neighbors, Artificial Neural Networks, MSE Cost function, and Gradient Descent parameter updates.


1. The Artificial Intelligence Hierarchy

Artificial Intelligence represents a broad spectrum of computational systems designed to perform tasks that typically require human intelligence. Within this overarching field, Machine Learning and Deep Learning form nested paradigms.

flowchart TD AI["Artificial Intelligence (AI)
Techniques that enable computers to mimic human intelligence
(Rule-Based Expert Systems + Learning Systems)"] ML["Machine Learning (ML)
Algorithms that improve automatically through data and experience
(Supervised, Unsupervised, Reinforcement)"] DL["Deep Learning (DL)
Multi-layered Artificial Neural Networks learning hierarchical representations
(CNN, RNN, Transformers)"] AI --> ML ML --> DL

1.1 Core Definitions & Taxonomy

  • Artificial Intelligence (AI): The overarching discipline concerned with building smart machines capable of performing cognitive tasks. AI encompasses both:
    • Rule-Driven Systems: Explicit hand-crafted if-then heuristics, expert systems, and symbolic logic engines.
    • Data-Driven Systems: Empirical statistical models that infer decision rules directly from data.
  • Machine Learning (ML): A subfield of AI that provides systems the ability to automatically learn and improve from experience without being explicitly programmed. A computer program is said to learn from experience EE with respect to task TT and performance measure PP if its performance at task TT, as measured by PP, improves with experience EE.
  • Deep Learning (DL): A specialized subset of ML based on Artificial Neural Networks with representation learning. Deep learning architectures pass inputs through dozens or hundreds of hidden layers, extracting abstract features hierarchically (e.g., edges โ†’\to textures โ†’\to object parts โ†’\to full objects).

1.2 Comparison: AI vs Machine Learning vs Deep Learning

Dimension Artificial Intelligence (AI) Machine Learning (ML) Deep Learning (DL)
Scope Broadest umbrella Subfield of AI Subfield of ML
Primary Approach Symbolic rules, heuristics, search, or statistical learning Statistical learning, cost optimization, decision boundaries Deep neural network architectures, backpropagation
Data Requirement Operates on rules or any data size Small to medium tabular / structured datasets Massive data scale required to prevent overfitting
Feature Extraction Manually encoded by domain experts Hand-crafted feature engineering (scaling, encoding, selection) Automatic end-to-end feature representation learning
Hardware Demand Standard CPU Standard CPU / multi-core CPU High-performance GPUs / TPUs for tensor calculations
Interpretability High in rule systems; variable in hybrid systems Moderate to high (Linear models, Decision trees) Black-box behavior; low direct interpretability

1.3 Notable Real-World Milestones

  • Google AlphaGo (2016): Defeated world champion Go master Lee Sedol using deep convolutional neural networks combined with Monte Carlo Tree Search (MCTS) and reinforcement learning.
  • Autonomous Driving: Multi-modal computer vision, LiDAR sensor fusion, and real-time path planning.
  • Natural Language Processing & Speech: Voice assistants, real-time speech-to-text, neural machine translation, and modern conversational Large Language Models (LLMs).
  • Computer Vision & Healthcare: Automated facial recognition, diagnostic medical imaging (tumor segmentation, diabetic retinopathy), and automated defect inspection in manufacturing.

2. Machine Learning Paradigms & Data Taxonomy

Machine learning systems are broadly categorized according to the nature of their supervisory feedback signal during training.

flowchart TD MLRoot["Machine Learning"] Supervised["Supervised Learning
(Labeled Target Provided)"] Unsupervised["Unsupervised Learning
(No Target Labels)"] RL["Reinforcement Learning
(Reward Signal / Environment)"] MLRoot --> Supervised MLRoot --> Unsupervised MLRoot --> RL Regression["Regression
(Continuous Numerical Target)"] Classification["Classification
(Discrete Categorical Target)"] Supervised --> Regression Supervised --> Classification Clustering["Clustering
(Group Discovery: K-Means, DBSCAN)"] DimReduction["Dimensionality Reduction
(Feature Compression: PCA, SVD)"] Unsupervised --> Clustering Unsupervised --> DimReduction

2.1 Supervised Learning

In supervised learning, the training algorithm receives a dataset consisting of input features paired with corresponding ground-truth target outputs:

D={(x(1),y(1)),(x(2),y(2)),โ€ฆ,(x(m),y(m))}\mathcal{D} = \left\{ (\mathbf{x}^{(1)}, y^{(1)}), (\mathbf{x}^{(2)}, y^{(2)}), \dots, (\mathbf{x}^{(m)}, y^{(m)}) \right\}

The objective is to learn a mapping function f:Xโ†’Yf: \mathcal{X} \to \mathcal{Y} such that f(x)f(\mathbf{x}) accurately predicts the true label yy on novel, unseen data.

  • Regression: The target variable yy is continuous (yโˆˆRy \in \mathbb{R}). Examples: predicting house sale prices, temperature, stock valuation, product demand.
  • Classification: The target variable yy is discrete and categorical (yโˆˆ{0,1}y \in \{0, 1\} or yโˆˆ{1,2,โ€ฆ,C}y \in \{1, 2, \dots, C\}). Examples: binary spam detection (spam vs ham), medical diagnosis (disease present vs absent), multi-class handwritten digit recognition (00 through 99).

2.2 Unsupervised Learning

In unsupervised learning, the training dataset consists exclusively of input features without target labels:

D={x(1),x(2),โ€ฆ,x(m)}\mathcal{D} = \left\{ \mathbf{x}^{(1)}, \mathbf{x}^{(2)}, \dots, \mathbf{x}^{(m)} \right\}

The algorithm must discover intrinsic patterns, latent structures, cluster boundaries, or lower-dimensional representations on its own:

  • Clustering: Partitioning data into cohesive groups where intra-cluster similarity is maximized and inter-cluster similarity is minimized (e.g., K-Means, DBSCAN).
  • Dimensionality Reduction: Compacting high-dimensional feature spaces while preserving maximum variance (e.g., Principal Component Analysis, SVD).

2.3 Mathematical Matrix Representation of Datasets

A dataset with mm sample instances and nn input features is represented as an mร—nm \times n feature matrix X\mathbf{X} and an mร—1m \times 1 target vector y\mathbf{y}:

X=[x1(1)x2(1)โ€ฆxn(1)x1(2)x2(2)โ€ฆxn(2)โ‹ฎโ‹ฎโ‹ฑโ‹ฎx1(m)x2(m)โ€ฆxn(m)]โˆˆRmร—n,y=[y(1)y(2)โ‹ฎy(m)]โˆˆRm\mathbf{X} = \begin{bmatrix} x_{1}^{(1)} & x_{2}^{(1)} & \dots & x_{n}^{(1)} \\ x_{1}^{(2)} & x_{2}^{(2)} & \dots & x_{n}^{(2)} \\ \vdots & \vdots & \ddots & \vdots \\ x_{1}^{(m)} & x_{2}^{(m)} & \dots & x_{n}^{(m)} \end{bmatrix} \in \mathbb{R}^{m \times n}, \quad \mathbf{y} = \begin{bmatrix} y^{(1)} \\ y^{(2)} \\ \vdots \\ y^{(m)} \end{bmatrix} \in \mathbb{R}^{m}

  • Independent Variables (Features / Inputs): Columns x1,x2,โ€ฆ,xnx_1, x_2, \dots, x_n representing measured attributes.
  • Dependent Variable (Label / Ground Truth): Column yy representing the target outcome to be predicted.

3. What is a Model? Candidate Model Comparison (Toy Dataset Study)

A model is a mathematical or algorithmic construct that formalizes the relationship between input features x\mathbf{x} and the target outcome yy:

y^=f(x)\hat{y} = f(\mathbf{x})

Where y^\hat{y} denotes the predicted value produced by the model, to be contrasted with the true label yy.

3.1 The 3-Point Toy Problem

Consider a minimal one-dimensional toy training dataset with 3 observation pairs:

Dtoy={(x=1,y=0),โ€…โ€Š(x=2,y=0),โ€…โ€Š(x=3,y=1)}\mathcal{D}_{\text{toy}} = \left\{ (x=1, y=0), \; (x=2, y=0), \; (x=3, y=1) \right\}

In the lecture slides (slides 29โ€“36), seven different mathematical and algorithmic formulations are proposed to fit these three data points. Below, progressive animation reveals are unified into one single comparative reference table.

3.2 Unified Candidate Model Comparison Table

# Model Paradigm Formulation / Implementation Predicted Output y^\hat{y} for xโˆˆ{1,2,3}x \in \{1, 2, 3\} Inductive Bias & Generalization Characteristics
1 Clamped Linear (ReLU-like) y=maxโก(xโˆ’2,0)y = \max(x - 2, 0) x=1โ†’0x=1 \to 0
x=2โ†’0x=2 \to 0
x=3โ†’1x=3 \to 1
Continuous piecewise linear function; outputs non-negative values; grows unbounded for x>3x > 3.
2 Scaled Rounding y=round(x5)y = \text{round}\left(\frac{x}{5}\right) x=1โ†’0x=1 \to 0
x=2โ†’0x=2 \to 0
x=3โ†’1x=3 \to 1
Step quantization; fragile thresholding dependent on denominator scaling factor.
3 Piecewise Step Function y={0,x<31,x=3y = \begin{cases} 0, & x < 3 \\ 1, & x = 3 \end{cases} x=1โ†’0x=1 \to 0
x=2โ†’0x=2 \to 0
x=3โ†’1x=3 \to 1
Exact point lookup; undefined behavior for inputs outside the observed domain (x>3x > 3).
4 Explicit Rule Enumeration if (x == 1) or (x == 2): y = 0
elif x == 3: y = 1
x=1โ†’0x=1 \to 0
x=2โ†’0x=2 \to 0
x=3โ†’1x=3 \to 1
Pure memorization; zero generalization capacity for unseen values such as x=2.5x = 2.5 or x=4x = 4.
5 Threshold Decision Rule if x <= 2: y = 0
else: y = 1
x=1โ†’0x=1 \to 0
x=2โ†’0x=2 \to 0
x=3โ†’1x=3 \to 1
Binary half-space partitioning; defines an explicit decision threshold at x=2x = 2.
6 Logistic / Sigmoid Function y=11+eโˆ’(ฮฒ0+ฮฒ1x)y = \frac{1}{1 + e^{-(\beta_0 + \beta_1 x)}} x=1โ†’โ‰ˆ0x=1 \to \approx 0
x=2โ†’โ‰ˆ0x=2 \to \approx 0
x=3โ†’โ‰ˆ1x=3 \to \approx 1
Smooth, differentiable probabilistic output strictly bounded in the open interval (0,1)(0, 1).
7 Decision Tree Node Split: [x<3][x < 3]
โ†’True:y=0\to \text{True}: y = 0
โ†’False:y=1\to \text{False}: y = 1
x=1โ†’0x=1 \to 0
x=2โ†’0x=2 \to 0
x=3โ†’1x=3 \to 1
Hierarchical axis-aligned partitioning; highly interpretable structure.

3.3 Generalizing to Multi-Feature Spaces

While 1D toy problems allow intuitive visualization, real-world data involves multiple features of mixed types (numerical, categorical, textual):

x=[x1,x2,x3,โ€ฆ,xn]Tโ€…โ€ŠโŸนโ€…โ€Šy^=f(x;W)\mathbf{x} = \left[ x_1, x_2, x_3, \dots, x_n \right]^T \implies \hat{y} = f(\mathbf{x}; \mathbf{W})

The challenge in machine learning is not merely memorizing the training samples, but selecting a model architecture and learning its parameter weights W\mathbf{W} such that it generalizes accurately to previously unseen data points.


4. End-to-End Machine Learning Workflow

An end-to-end supervised machine learning pipeline consists of systematic phases: data ingestion, data splitting, training, inference, and metric evaluation.

4.1 Pipeline Architecture Diagram

flowchart TD RawData["Raw Dataset (X, y)
Feature Matrix X and Ground-Truth Labels y"] SplitNode["train_test_split(X, y, test_size=0.3)
Partition Data into Disjoint Subsets"] XTrain["X_train
Training Features"] YTrain["y_train
Training Labels"] XTest["X_test
Test Features (Unseen)"] YTest["y_test
Ground Truth Labels"] TrainBlock["Model Training
model.fit(X_train, y_train)
Optimize Parameters W"] ModelInstance["Trained Model Instance
Learned Parameters (Weights w, Bias b)"] PredictBlock["Inference / Prediction
y_pred = model.predict(X_test)"] EvalBlock["Performance Evaluation
metric(y_test, y_pred)
Compare Predictions vs Ground Truth"] RawData --> SplitNode SplitNode --> XTrain SplitNode --> YTrain SplitNode --> XTest SplitNode --> YTest XTrain --> TrainBlock YTrain --> TrainBlock TrainBlock --> ModelInstance XTest --> PredictBlock ModelInstance --> PredictBlock PredictBlock --> EvalBlock YTest --> EvalBlock

4.2 Detailed Workflow Stages

  1. Dataset Partitioning (Train-Test Split):

    • The original dataset (X,y)(\mathbf{X}, \mathbf{y}) is partitioned into two disjoint subsets:
      • Training Set (Xtrain,ytrain)(\mathbf{X}_{\text{train}}, \mathbf{y}_{\text{train}}): Used exclusively by the learning algorithm to adjust model parameters.
      • Test Set (Xtest,ytest)(\mathbf{X}_{\text{test}}, \mathbf{y}_{\text{test}}): Held out strictly as unseen evaluation data. No training information may leak into this set.
    • Standard split ratios include 70/3070/30, 75/2575/25, or 80/2080/20.
  2. Model Training (.fit()):

    • The estimator takes Xtrain\mathbf{X}_{\text{train}} and ytrain\mathbf{y}_{\text{train}}, minimizes a chosen loss or cost function, and learns optimal internal parameters (coefficients, decision splits, or neural synaptic weights).
  3. Inference / Prediction (.predict()):

    • The fitted model receives Xtest\mathbf{X}_{\text{test}} without labels and generates predicted output values y^pred\hat{\mathbf{y}}_{\text{pred}}.
  4. Performance Evaluation:

    • The predicted values y^pred\hat{\mathbf{y}}_{\text{pred}} are quantitatively compared against actual ground-truth labels ytest\mathbf{y}_{\text{test}} using domain-appropriate error metrics.
  5. Cross-Validation Synergy:

    • While a single train-test split provides a quick estimate, it is subject to sampling variance. K-Fold Cross-Validation (detailed in the course personal notes at notes/k-fold-cross-validation.md) partitions data into KK equal folds, iteratively training on Kโˆ’1K-1 folds and testing on the remaining fold, then averaging test metrics e1,e2,โ€ฆ,eKe_1, e_2, \dots, e_K across all KK rounds.

5. Regression Evaluation Metrics

In regression problems, predictions y^i\hat{y}_i and actual targets yiy_i are continuous real numbers. The discrepancy between actual and predicted values for sample ii is the residual error:

ei=yiโˆ’y^ie_i = y_i - \hat{y}_i

Evaluation metrics aggregate these residual errors across all nn samples in the evaluation set.

5.1 Standard Mathematical Formulas

Mean Absolute Error (MAE)

Computes the arithmetic average of absolute errors. Linear penalty; robust to outliers:

MAE=1nโˆ‘i=1nโˆฃyiโˆ’y^iโˆฃ\text{MAE} = \frac{1}{n} \sum_{i=1}^{n} |y_i - \hat{y}_i|

Mean Squared Error (MSE)

Computes the arithmetic average of squared errors. Penalizes larger deviations much more severely than small ones due to the quadratic power:

MSE=1nโˆ‘i=1n(yiโˆ’y^i)2\text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2

Root Mean Squared Error (RMSE)

The square root of MSE. Restores error units to the original physical scale of the target variable yy, making it directly interpretable:

RMSE=1nโˆ‘i=1n(yiโˆ’y^i)2\text{RMSE} = \sqrt{\frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2}

Mean Absolute Percentage Error (MAPE)

Measures the relative error percentage with respect to the true magnitude of yiy_i. Invariant to global scale:

MAPE=100%nโˆ‘i=1nโˆฃyiโˆ’y^iyiโˆฃ\text{MAPE} = \frac{100\%}{n} \sum_{i=1}^{n} \left| \frac{y_i - \hat{y}_i}{y_i} \right|

Coefficient of Determination (R2R^2 Score)

Measures the proportion of variance in the dependent variable explained by the independent features in the model, relative to a baseline horizontal mean predictor:

R2=1โˆ’SSresSStot=1โˆ’โˆ‘i=1n(yiโˆ’y^i)2โˆ‘i=1n(yiโˆ’yห‰)2R^2 = 1 - \frac{SS_{\text{res}}}{SS_{\text{tot}}} = 1 - \frac{\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}{\sum_{i=1}^{n} (y_i - \bar{y})^2}

Where:

  • SSres=โˆ‘i=1n(yiโˆ’y^i)2SS_{\text{res}} = \sum_{i=1}^n (y_i - \hat{y}_i)^2 is the residual sum of squares.
  • SStot=โˆ‘i=1n(yiโˆ’yห‰)2SS_{\text{tot}} = \sum_{i=1}^n (y_i - \bar{y})^2 is the total sum of squares.
  • yห‰=1nโˆ‘i=1nyi\bar{y} = \frac{1}{n} \sum_{i=1}^n y_i is the empirical sample mean of target values.
  • R2=1.0R^2 = 1.0 represents a perfect fit (SSres=0SS_{\text{res}} = 0).
  • R2=0.0R^2 = 0.0 indicates the model performs no better than constantly predicting yห‰\bar{y}.
  • R2<0.0R^2 < 0.0 indicates the model performs worse than the simple sample mean.

5.2 Step-by-Step Numerical Walkthrough (Slide 52 Dataset)

To illustrate the exact mechanics of regression error calculation, we walk through the exact 3-case example presented on slide 52 of the lecture deck:

D={(y1=10,y^1=8),โ€…โ€Š(y2=20,y^2=21),โ€…โ€Š(y3=30,y^3=32)},n=3\mathcal{D} = \left\{ (y_1 = 10, \hat{y}_1 = 8), \; (y_2 = 20, \hat{y}_2 = 21), \; (y_3 = 30, \hat{y}_3 = 32) \right\}, \quad n = 3

Case ii Actual Target yiy_i Predicted Target y^i\hat{y}_i Residual (yiโˆ’y^i)(y_i - \hat{y}_i) Absolute Error โˆฃyiโˆ’y^iโˆฃ|y_i - \hat{y}_i| Squared Error (yiโˆ’y^i)2(y_i - \hat{y}_i)^2 Percentage Error โˆฃyiโˆ’y^iโˆฃyi\frac{|y_i - \hat{y}_i|}{y_i}
1 1010 88 10โˆ’8=+210 - 8 = +2 โˆฃ+2โˆฃ=2|+2| = 2 (+2)2=4(+2)^2 = 4 210=0.200\frac{2}{10} = 0.200
2 2020 2121 20โˆ’21=โˆ’120 - 21 = -1 โˆฃโˆ’1โˆฃ=1|-1| = 1 (โˆ’1)2=1(-1)^2 = 1 120=0.050\frac{1}{20} = 0.050
3 3030 3232 30โˆ’32=โˆ’230 - 32 = -2 โˆฃโˆ’2โˆฃ=2|-2| = 2 (โˆ’2)2=4(-2)^2 = 4 230โ‰ˆ0.0667\frac{2}{30} \approx 0.0667
Sum โˆ‘=60\sum = 60 โˆ‘=61\sum = 61 โˆ‘=โˆ’1\sum = -1 โˆ‘=5\sum = 5 โˆ‘=9\sum = 9 โˆ‘โ‰ˆ0.3167\sum \approx 0.3167

Arithmetic Derivation:

  1. Mean Absolute Error (MAE):

    MAE=13(2+1+2)=53โ‰ˆ1.667\text{MAE} = \frac{1}{3} \left( 2 + 1 + 2 \right) = \frac{5}{3} \approx 1.667

  2. Mean Squared Error (MSE):

    MSE=13(4+1+4)=93=3.0\text{MSE} = \frac{1}{3} \left( 4 + 1 + 4 \right) = \frac{9}{3} = 3.0

  3. Root Mean Squared Error (RMSE):

    RMSE=MSE=3.0โ‰ˆ1.732\text{RMSE} = \sqrt{\text{MSE}} = \sqrt{3.0} \approx 1.732

    (Verifies the verbatim value RMSE=1.732\text{RMSE} = 1.732 on Slide 52).

  4. Mean Absolute Percentage Error (MAPE):

    MAPE=100%3(0.200+0.050+0.0667)=100%3(0.3167)โ‰ˆ10.56%\text{MAPE} = \frac{100\%}{3} \left( 0.200 + 0.050 + 0.0667 \right) = \frac{100\%}{3} (0.3167) \approx 10.56\%

  5. Coefficient of Determination (R2R^2):

    yห‰=10+20+303=20\bar{y} = \frac{10 + 20 + 30}{3} = 20

    SStot=(10โˆ’20)2+(20โˆ’20)2+(30โˆ’20)2=(โˆ’10)2+02+(10)2=100+0+100=200SS_{\text{tot}} = (10 - 20)^2 + (20 - 20)^2 + (30 - 20)^2 = (-10)^2 + 0^2 + (10)^2 = 100 + 0 + 100 = 200

    SSres=4+1+4=9SS_{\text{res}} = 4 + 1 + 4 = 9

    R2=1โˆ’9200=1โˆ’0.045=0.955R^2 = 1 - \frac{9}{200} = 1 - 0.045 = 0.955


6. Classification Evaluation Introduction

In classification, predictions represent discrete qualitative labels. Evaluating a classifier involves comparing true category membership against model predictions.

6.1 The 2ร—22 \times 2 Confusion Matrix

For a binary classification task (e.g. classifying whether a sample is a Human vs Not Human, or Positive vs Negative), predictions fall into four mutually exclusive categories:

Predicted Positive (y^=1\hat{y} = 1) Predicted Negative (y^=0\hat{y} = 0)
Actual Positive (y=1y = 1) True Positive (TPTP) False Negative (FNFN)
Actual Negative (y=0y = 0) False Positive (FPFP) True Negative (TNTN)
  • True Positive (TPTP): Model correctly predicted positive condition.
  • True Negative (TNTN): Model correctly predicted negative condition.
  • False Positive (FPFP): Type I error; model predicted positive when actual was negative (false alarm).
  • False Negative (FNFN): Type II error; model predicted negative when actual was positive (missed detection).

6.2 Accuracy Metric & Slide 59 Numerical Drill

Accuracy computes the ratio of all correctly classified instances over the total population size:

Accuracy=TP+TNTP+TN+FP+FN\text{Accuracy} = \frac{TP + TN}{TP + TN + FP + FN}

Slide 59 Worked Matrix:

The lecture presents the following confusion counts:

Predicted Yes Predicted No Total Actual
Actual Yes TP=4TP = 4 FN=1FN = 1 55
Actual No FP=2FP = 2 TN=3TN = 3 55
Total Predicted 66 44 N=10N = 10

Calculation:

Accuracy=4+34+3+1+2=710=0.70(70%)\text{Accuracy} = \frac{4 + 3}{4 + 3 + 1 + 2} = \frac{7}{10} = 0.70 \quad (70\%)

(Note: Slide 59 contains a CambriaMath shifted font rendering in the original slide deck, which precisely decodes to the numbers 4+34+3+1+2=0.70\frac{4 + 3}{4 + 3 + 1 + 2} = 0.70).

6.3 Associated Core Classification Metrics

  • Precision (Positive Predictive Value): What proportion of predicted positives were truly positive?

    Precision=TPTP+FP=44+2=46โ‰ˆ0.667\text{Precision} = \frac{TP}{TP + FP} = \frac{4}{4 + 2} = \frac{4}{6} \approx 0.667

  • Recall (Sensitivity / True Positive Rate): What proportion of actual positives were successfully found?

    Recall=TPTP+FN=44+1=45=0.800\text{Recall} = \frac{TP}{TP + FN} = \frac{4}{4 + 1} = \frac{4}{5} = 0.800

  • F1F_1-Score: The harmonic mean of Precision and Recall:

    F1=2โ‹…Precisionโ‹…RecallPrecision+Recall=2โ‹…0.667โ‹…0.8000.667+0.800โ‰ˆ0.727F_1 = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}} = 2 \cdot \frac{0.667 \cdot 0.800}{0.667 + 0.800} \approx 0.727


7. Key Machine Learning Algorithms Overview

The lecture introduces six foundational machine learning algorithms spanning regression and classification paradigms.

7.1 Linear Regression

Linear regression models the relationship between dependent scalar yy and one or more explanatory variables x\mathbf{x} as a linear combination.

  • Univariate Formulation:

    y=w1x+w0ory=mx+cy = w_1 x + w_0 \quad \text{or} \quad y = mx + c

    Where w1w_1 (or mm) represents slope, and w0w_0 (or cc) represents the y-intercept.
  • Multivariate Formulation:

    y=ฮฒ0+ฮฒ1x1+ฮฒ2x2+โ‹ฏ+ฮฒkxk=wTx+by = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \dots + \beta_k x_k = \mathbf{w}^T \mathbf{x} + b

  • Feature Selection: Prior to fitting, pairwise Pearson correlation coefficients rxyโˆˆ[โˆ’1,1]r_{xy} \in [-1, 1] are examined to identify input variables with high explanatory power and eliminate redundant multi-collinear features.

7.2 Decision Tree Classifier

Decision trees partition the input feature space into rectangular decision regions through recursive hierarchical if-else threshold tests.

  • Internal nodes represent attribute evaluation conditions.
  • Leaf nodes represent terminal class assignments.
  • Non-parametric; requires minimal feature scaling; fully interpretable. (Covered in full depth in Lecture 05: 05-decision-tree.md).

7.3 Logistic Regression

Despite its name, Logistic Regression is a binary classification algorithm. It maps linear combinations of input features to bounded probabilities using the non-linear Sigmoid Activation Function:

ฯƒ(z)=11+eโˆ’z\sigma(z) = \frac{1}{1 + e^{-z}}

Where the logit zz is a linear model:

z=ฮฒ0+ฮฒ1x1+ฮฒ2x2+โ‹ฏ+ฮฒnxn=wTx+bz = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \dots + \beta_n x_n = \mathbf{w}^T \mathbf{x} + b

Substituting zz into the sigmoid equation yields:

P(y=1โˆฃx)=11+eโˆ’(ฮฒ0+ฮฒ1x1+โ‹ฏ+ฮฒnxn)P(y = 1 \mid \mathbf{x}) = \frac{1}{1 + e^{-(\beta_0 + \beta_1 x_1 + \dots + \beta_n x_n)}}

  • When zโ†’+โˆžz \to +\infty, ฯƒ(z)โ†’1\sigma(z) \to 1.
  • When zโ†’โˆ’โˆžz \to -\infty, ฯƒ(z)โ†’0\sigma(z) \to 0.
  • When z=0z = 0, ฯƒ(0)=0.5\sigma(0) = 0.5 (the default decision threshold: predict y^=1\hat{y} = 1 if Pโ‰ฅ0.5P \ge 0.5).

7.4 Naรฏve Bayes

Naรฏve Bayes is a probabilistic classifier founded upon Bayesโ€™ Theorem, with the โ€œnaรฏveโ€ assumption of conditional independence among features given the class label.

  • Bayesโ€™ Theorem:

    P(yโˆฃx)=P(xโˆฃy)P(y)P(x)P(y \mid \mathbf{x}) = \frac{P(\mathbf{x} \mid y) P(y)}{P(\mathbf{x})}

  • Conditional Independence Assumption:

    P(x1,x2,โ€ฆ,xnโˆฃy)=โˆi=1nP(xiโˆฃy)P(x_1, x_2, \dots, x_n \mid y) = \prod_{i=1}^{n} P(x_i \mid y)

  • Classification Decision Rule:

    y^=argโกmaxโกyโˆˆYP(y)โˆi=1nP(xiโˆฃy)\hat{y} = \arg\max_{y \in \mathcal{Y}} P(y) \prod_{i=1}^{n} P(x_i \mid y)

  • Fast, scalable, highly effective for text classification and high-dimensional categorical problems.

7.5 K-Nearest Neighbors (KNN)

KNN is an instance-based (lazy learning), non-parametric algorithm. It makes no explicit assumptions about the underlying distribution of data and delays all computation until query time.

  • Distance Metric: The proximity between a query point xq\mathbf{x}_q and training instance xi\mathbf{x}_i is typically calculated via Euclidean distance:

    d(xq,xi)=โˆ‘j=1n(xq,jโˆ’xi,j)2d(\mathbf{x}_q, \mathbf{x}_i) = \sqrt{\sum_{j=1}^{n} \left( x_{q,j} - x_{i,j} \right)^2}

  • Decision Behavior Dependent on KK (Slides 119โ€“122):
    • K=1K = 1: Assigns the class of the single nearest neighbor. Extremely flexible boundary, but highly sensitive to noise and outliers.
    • K=2K = 2: Identifies 2 nearest neighbors. If each neighbor belongs to a different class, a tie occurs (Class=???\text{Class} = \text{???}), requiring tie-breaking rules.
    • K=3K = 3: An odd KK avoids binary ties; majority vote determines the winning class. Smoother, more robust decision boundary.
flowchart LR QueryPoint["Query Point (x1, x2)"] K1["K = 1 Nearest Neighbor
Predicts: Triangle"] K2["K = 2 Nearest Neighbors
1 Triangle, 1 Square
Tie / Indeterminate!"] K3["K = 3 Nearest Neighbors
1 Triangle, 2 Squares
Majority Vote: Square"] QueryPoint --> K1 QueryPoint --> K2 QueryPoint --> K3

7.6 Artificial Neural Networks (ANN)

Artificial Neural Networks are biologically inspired computational networks composed of interconnected processing units (neurons / perceptrons) arranged in layers.

  • The Single Perceptron Model (Slide 127): A single neuron computes a weighted sum of inputs plus a bias term, followed by an activation function:

    h(X)=w0+w1x1+w2x2=wTx+bh(\mathbf{X}) = w_0 + w_1 x_1 + w_2 x_2 = \mathbf{w}^T \mathbf{x} + b

    y^=g(h(X))=11+eโˆ’h(X)\hat{y} = g(h(\mathbf{X})) = \frac{1}{1 + e^{-h(\mathbf{X})}}

  • Layered Multi-Layer Perceptron (MLP) Architecture (Slide 128):
    • Input Layer: Transmits raw feature attributes x1,x2,โ€ฆ,xnx_1, x_2, \dots, x_n.
    • Hidden Layers: One or more intermediate layers where each neuron extracts non-linear feature combinations.
    • Output Layer: Produces final prediction y^\hat{y} (scalar for regression, probability vector for classification).
  • Feedforward Propagation: Information travels strictly forward from input nodes โ†’\to hidden layers โ†’\to output nodes.
  • Backpropagation: Error gradients are propagated backwards through the network to iteratively update synaptic weights.

8. Optimization: Cost Functions and Gradient Descent

Learning in parameterized models (Linear Regression, Logistic Regression, Neural Networks) is formulated as an optimization problem: finding the weight vector W\mathbf{W} that minimizes an empirical cost function across all training instances.

8.1 The Mean Squared Error Cost Function J(W)J(\mathbf{W})

For a dataset of mm training samples, the Mean Squared Error (MSE) cost function J(W)J(\mathbf{W}) is defined as:

J(W)=12mโˆ‘i=1m(y^(i)โˆ’y(i))2J(\mathbf{W}) = \frac{1}{2m} \sum_{i=1}^{m} \left( \hat{y}^{(i)} - y^{(i)} \right)^2

Where:

  • mm is the total number of training samples.
  • y(i)y^{(i)} is the actual target value of the ii-th sample.
  • y^(i)\hat{y}^{(i)} is the modelโ€™s predicted value for the ii-th sample:

    y^(i)=w0+w1x1(i)+w2x2(i)+โ‹ฏ+wnxn(i)=โˆ‘j=0nwjxj(i)(withย x0(i)=1)\hat{y}^{(i)} = w_0 + w_1 x_1^{(i)} + w_2 x_2^{(i)} + \dots + w_n x_n^{(i)} = \sum_{j=0}^{n} w_j x_j^{(i)} \quad (\text{with } x_0^{(i)} = 1)

  • The coefficient 12\frac{1}{2} is an algebraic convenience: when differentiating (y^(i)โˆ’y(i))2\left(\hat{y}^{(i)} - y^{(i)}\right)^2, the exponent 22 cancels cleanly with 12\frac{1}{2}.

8.2 Gradient Descent Parameter Update Rule

Gradient Descent is an iterative first-order optimization algorithm that steps parameter weights in the direction opposite to the gradient of the cost surface:

wj:=wjโˆ’ฮฑโˆ‚โˆ‚wjJ(W)w_j := w_j - \alpha \frac{\partial}{\partial w_j} J(\mathbf{W})

Where:

  • wjw_j is the jj-th parameter weight.
  • ฮฑ>0\alpha > 0 is the learning rate (step size). If ฮฑ\alpha is too small, convergence is slow; if ฮฑ\alpha is too large, the algorithm can oscillate or diverge.
  • โˆ‚โˆ‚wjJ(W)\frac{\partial}{\partial w_j} J(\mathbf{W}) is the partial derivative of the cost function with respect to weight wjw_j.
  • Updates across all weights jโˆˆ{0,1,โ€ฆ,n}j \in \{0, 1, \dots, n\} must be performed simultaneously at each iteration.

8.3 Chain Rule Derivation of the Gradient (Slide 132)

Applying the multivariable calculus chain rule to derive โˆ‚โˆ‚wjJ(W)\frac{\partial}{\partial w_j} J(\mathbf{W}):

โˆ‚โˆ‚wjJ(W)=โˆ‚โˆ‚wj[12mโˆ‘i=1m(y^(i)โˆ’y(i))2]\frac{\partial}{\partial w_j} J(\mathbf{W}) = \frac{\partial}{\partial w_j} \left[ \frac{1}{2m} \sum_{i=1}^{m} \left( \hat{y}^{(i)} - y^{(i)} \right)^2 \right]

Pass the derivative inside the summation:

โˆ‚โˆ‚wjJ(W)=12mโˆ‘i=1mโˆ‚โˆ‚wj(y^(i)โˆ’y(i))2\frac{\partial}{\partial w_j} J(\mathbf{W}) = \frac{1}{2m} \sum_{i=1}^{m} \frac{\partial}{\partial w_j} \left( \hat{y}^{(i)} - y^{(i)} \right)^2

Apply the chain rule: โˆ‚โˆ‚u(u2)=2uโ‹…โˆ‚uโˆ‚wj\frac{\partial}{\partial u} (u^2) = 2u \cdot \frac{\partial u}{\partial w_j}:

โˆ‚โˆ‚wjJ(W)=12mโˆ‘i=1m2(y^(i)โˆ’y(i))โ‹…โˆ‚โˆ‚wj(y^(i)โˆ’y(i))\frac{\partial}{\partial w_j} J(\mathbf{W}) = \frac{1}{2m} \sum_{i=1}^{m} 2 \left( \hat{y}^{(i)} - y^{(i)} \right) \cdot \frac{\partial}{\partial w_j} \left( \hat{y}^{(i)} - y^{(i)} \right)

Cancel the factor of 2:

โˆ‚โˆ‚wjJ(W)=1mโˆ‘i=1m(y^(i)โˆ’y(i))โ‹…โˆ‚y^(i)โˆ‚wj\frac{\partial}{\partial w_j} J(\mathbf{W}) = \frac{1}{m} \sum_{i=1}^{m} \left( \hat{y}^{(i)} - y^{(i)} \right) \cdot \frac{\partial \hat{y}^{(i)}}{\partial w_j}

Since y^(i)=w0x0(i)+w1x1(i)+โ‹ฏ+wjxj(i)+โ‹ฏ+wnxn(i)\hat{y}^{(i)} = w_0 x_0^{(i)} + w_1 x_1^{(i)} + \dots + w_j x_j^{(i)} + \dots + w_n x_n^{(i)}, the partial derivative with respect to wjw_j is simply the feature value xj(i)x_j^{(i)}:

โˆ‚y^(i)โˆ‚wj={1,forย j=0ย (biasย termย w0)xj(i),forย jโ‰ฅ1\frac{\partial \hat{y}^{(i)}}{\partial w_j} = \begin{cases} 1, & \text{for } j = 0 \text{ (bias term } w_0) \\ x_j^{(i)}, & \text{for } j \ge 1 \end{cases}

Substituting back into the gradient formula yields the canonical update equation:

โˆ‚โˆ‚wjJ(W)=1mโˆ‘i=1m(y^(i)โˆ’y(i))xj(i)\frac{\partial}{\partial w_j} J(\mathbf{W}) = \frac{1}{m} \sum_{i=1}^{m} \left( \hat{y}^{(i)} - y^{(i)} \right) x_j^{(i)}

And the complete iterative weight update becomes:

wj:=wjโˆ’ฮฑ1mโˆ‘i=1m(y^(i)โˆ’y(i))xj(i)w_j := w_j - \alpha \frac{1}{m} \sum_{i=1}^{m} \left( \hat{y}^{(i)} - y^{(i)} \right) x_j^{(i)}


9. Scikit-Learn Python Implementation Guide

The Scikit-Learn API provides a standardized interface across all learning algorithms:

# ==============================================================================
# End-to-End Supervised Learning Template (Scikit-Learn)
# ==============================================================================
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import mean_squared_error, accuracy_score

# 1. Ingest Data
df = pd.read_csv('dataset.csv')
X = df[['feature_1', 'feature_2', 'feature_3']]
y = df['target']

# 2. Train-Test Split (Holdout Validation)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.30, random_state=42
)

# 3. Instantiate and Train Estimator
reg_model = LinearRegression()
reg_model.fit(X_train, y_train)

# 4. Generate Predictions on Held-Out Test Set
y_pred_reg = reg_model.predict(X_test)

# 5. Evaluate Performance Metric
mse = mean_squared_error(y_test, y_pred_reg)
rmse = mean_squared_error(y_test, y_pred_reg, squared=False)
print(f"Test MSE: {mse:.4f}, Test RMSE: {rmse:.4f}")

# Classification Alternative:
clf_model = DecisionTreeClassifier(random_state=42)
clf_model.fit(X_train, y_train)
y_pred_clf = clf_model.predict(X_test)
acc = accuracy_score(y_test, y_pred_clf)
print(f"Classification Accuracy: {acc * 100:.2f}%")

10. Summary & Key Concept Checklist

  • [x] AI / ML / DL Hierarchy: AI โŠƒ\supset ML โŠƒ\supset DL. AI includes rule-based heuristics; ML learns patterns from data; DL utilizes deep neural representations.
  • [x] Learning Paradigms: Supervised (labels provided: Regression for continuous yy, Classification for discrete yy), Unsupervised (no labels: Clustering and Dimensionality Reduction).
  • [x] Candidate Model Deduplication: 7 mathematical models for Dtoy={(1,0),(2,0),(3,1)}\mathcal{D}_{\text{toy}} = \{(1,0), (2,0), (3,1)\} consolidated into 1 unified comparative specification.
  • [x] Regression Metrics: MAE (1nโˆ‘โˆฃyโˆ’y^โˆฃ\frac{1}{n}\sum |y - \hat{y}|), MSE (1nโˆ‘(yโˆ’y^)2\frac{1}{n}\sum (y - \hat{y})^2), RMSE (MSE\sqrt{\text{MSE}}), MAPE (100%nโˆ‘โˆฃyโˆ’y^yโˆฃ\frac{100\%}{n}\sum |\frac{y - \hat{y}}{y}|), and R2R^2 (1โˆ’SSresSStot1 - \frac{SS_{\text{res}}}{SS_{\text{tot}}}).
  • [x] Classification Evaluation: 2ร—22 \times 2 Confusion Matrix (TP,TN,FP,FNTP, TN, FP, FN), Accuracy (TP+TNTotal\frac{TP+TN}{\text{Total}}), Precision, Recall, and F1F_1-Score.
  • [x] Core Algorithms: Linear Regression (y=wTx+by = \mathbf{w}^T \mathbf{x} + b), Decision Tree, Logistic Regression Sigmoid (11+eโˆ’z\frac{1}{1 + e^{-z}}), Naive Bayes, KNN (K=1,2,3K=1, 2, 3 tie behavior), and Neural Networks.
  • [x] Cost Optimization: MSE Cost Function J(W)=12mโˆ‘(y^(i)โˆ’y(i))2J(\mathbf{W}) = \frac{1}{2m}\sum (\hat{y}^{(i)} - y^{(i)})^2 and simultaneous Gradient Descent update wj:=wjโˆ’ฮฑ1mโˆ‘(y^(i)โˆ’y(i))xj(i)w_j := w_j - \alpha \frac{1}{m}\sum (\hat{y}^{(i)} - y^{(i)}) x_j^{(i)}.