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, ), 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.
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 with respect to task and performance measure if its performance at task , as measured by , improves with experience .
- 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 textures object parts 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.
(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:
The objective is to learn a mapping function such that accurately predicts the true label on novel, unseen data.
- Regression: The target variable is continuous (). Examples: predicting house sale prices, temperature, stock valuation, product demand.
- Classification: The target variable is discrete and categorical ( or ). Examples: binary spam detection (spam vs ham), medical diagnosis (disease present vs absent), multi-class handwritten digit recognition ( through ).
2.2 Unsupervised Learning
In unsupervised learning, the training dataset consists exclusively of input features without target labels:
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 sample instances and input features is represented as an feature matrix and an target vector :
- Independent Variables (Features / Inputs): Columns representing measured attributes.
- Dependent Variable (Label / Ground Truth): Column 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 and the target outcome :
Where denotes the predicted value produced by the model, to be contrasted with the true label .
3.1 The 3-Point Toy Problem
Consider a minimal one-dimensional toy training dataset with 3 observation pairs:
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 for | Inductive Bias & Generalization Characteristics |
|---|---|---|---|---|
| 1 | Clamped Linear (ReLU-like) | Continuous piecewise linear function; outputs non-negative values; grows unbounded for . | ||
| 2 | Scaled Rounding | Step quantization; fragile thresholding dependent on denominator scaling factor. | ||
| 3 | Piecewise Step Function | Exact point lookup; undefined behavior for inputs outside the observed domain (). | ||
| 4 | Explicit Rule Enumeration | if (x == 1) or (x == 2): y = 0elif x == 3: y = 1 |
Pure memorization; zero generalization capacity for unseen values such as or . | |
| 5 | Threshold Decision Rule | if x <= 2: y = 0else: y = 1 |
Binary half-space partitioning; defines an explicit decision threshold at . | |
| 6 | Logistic / Sigmoid Function | Smooth, differentiable probabilistic output strictly bounded in the open interval . | ||
| 7 | Decision Tree Node | Split: |
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):
The challenge in machine learning is not merely memorizing the training samples, but selecting a model architecture and learning its parameter weights 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
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
-
Dataset Partitioning (Train-Test Split):
- The original dataset is partitioned into two disjoint subsets:
- Training Set : Used exclusively by the learning algorithm to adjust model parameters.
- Test Set : Held out strictly as unseen evaluation data. No training information may leak into this set.
- Standard split ratios include , , or .
- The original dataset is partitioned into two disjoint subsets:
-
Model Training (
.fit()):- The estimator takes and , minimizes a chosen loss or cost function, and learns optimal internal parameters (coefficients, decision splits, or neural synaptic weights).
-
Inference / Prediction (
.predict()):- The fitted model receives without labels and generates predicted output values .
-
Performance Evaluation:
- The predicted values are quantitatively compared against actual ground-truth labels using domain-appropriate error metrics.
-
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 equal folds, iteratively training on folds and testing on the remaining fold, then averaging test metrics across all rounds.
- 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
5. Regression Evaluation Metrics
In regression problems, predictions and actual targets are continuous real numbers. The discrepancy between actual and predicted values for sample is the residual error:
Evaluation metrics aggregate these residual errors across all 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:
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:
Root Mean Squared Error (RMSE)
The square root of MSE. Restores error units to the original physical scale of the target variable , making it directly interpretable:
Mean Absolute Percentage Error (MAPE)
Measures the relative error percentage with respect to the true magnitude of . Invariant to global scale:
Coefficient of Determination ( 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:
Where:
- is the residual sum of squares.
- is the total sum of squares.
- is the empirical sample mean of target values.
- represents a perfect fit ().
- indicates the model performs no better than constantly predicting .
- 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:
| Case | Actual Target | Predicted Target | Residual | Absolute Error | Squared Error | Percentage Error |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | ||||||
| 3 | ||||||
| Sum |
Arithmetic Derivation:
-
Mean Absolute Error (MAE):
-
Mean Squared Error (MSE):
-
Root Mean Squared Error (RMSE):
(Verifies the verbatim value on Slide 52).
-
Mean Absolute Percentage Error (MAPE):
-
Coefficient of Determination ():
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 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 () | Predicted Negative () | |
|---|---|---|
| Actual Positive () | True Positive () | False Negative () |
| Actual Negative () | False Positive () | True Negative () |
- True Positive (): Model correctly predicted positive condition.
- True Negative (): Model correctly predicted negative condition.
- False Positive (): Type I error; model predicted positive when actual was negative (false alarm).
- False Negative (): 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:
Slide 59 Worked Matrix:
The lecture presents the following confusion counts:
| Predicted Yes | Predicted No | Total Actual | |
|---|---|---|---|
| Actual Yes | |||
| Actual No | |||
| Total Predicted |
Calculation:
(Note: Slide 59 contains a CambriaMath shifted font rendering in the original slide deck, which precisely decodes to the numbers ).
6.3 Associated Core Classification Metrics
- Precision (Positive Predictive Value): What proportion of predicted positives were truly positive?
- Recall (Sensitivity / True Positive Rate): What proportion of actual positives were successfully found?
- -Score: The harmonic mean of Precision and Recall:
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 and one or more explanatory variables as a linear combination.
- Univariate Formulation:
Where (or ) represents slope, and (or ) represents the y-intercept.
- Multivariate Formulation:
- Feature Selection: Prior to fitting, pairwise Pearson correlation coefficients 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:
Where the logit is a linear model:
Substituting into the sigmoid equation yields:
- When , .
- When , .
- When , (the default decision threshold: predict if ).
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:
- Conditional Independence Assumption:
- Classification Decision Rule:
- 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 and training instance is typically calculated via Euclidean distance:
- Decision Behavior Dependent on (Slides 119โ122):
- : Assigns the class of the single nearest neighbor. Extremely flexible boundary, but highly sensitive to noise and outliers.
- : Identifies 2 nearest neighbors. If each neighbor belongs to a different class, a tie occurs (), requiring tie-breaking rules.
- : An odd avoids binary ties; majority vote determines the winning class. Smoother, more robust decision boundary.
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:
- Layered Multi-Layer Perceptron (MLP) Architecture (Slide 128):
- Input Layer: Transmits raw feature attributes .
- Hidden Layers: One or more intermediate layers where each neuron extracts non-linear feature combinations.
- Output Layer: Produces final prediction (scalar for regression, probability vector for classification).
- Feedforward Propagation: Information travels strictly forward from input nodes hidden layers 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 that minimizes an empirical cost function across all training instances.
8.1 The Mean Squared Error Cost Function
For a dataset of training samples, the Mean Squared Error (MSE) cost function is defined as:
Where:
- is the total number of training samples.
- is the actual target value of the -th sample.
- is the modelโs predicted value for the -th sample:
- The coefficient is an algebraic convenience: when differentiating , the exponent cancels cleanly with .
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:
Where:
- is the -th parameter weight.
- is the learning rate (step size). If is too small, convergence is slow; if is too large, the algorithm can oscillate or diverge.
- is the partial derivative of the cost function with respect to weight .
- Updates across all weights 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 :
Pass the derivative inside the summation:
Apply the chain rule: :
Cancel the factor of 2:
Since , the partial derivative with respect to is simply the feature value :
Substituting back into the gradient formula yields the canonical update equation:
And the complete iterative weight update becomes:
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 ML 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 , Classification for discrete ), Unsupervised (no labels: Clustering and Dimensionality Reduction).
- [x] Candidate Model Deduplication: 7 mathematical models for consolidated into 1 unified comparative specification.
- [x] Regression Metrics: MAE (), MSE (), RMSE (), MAPE (), and ().
- [x] Classification Evaluation: Confusion Matrix (), Accuracy (), Precision, Recall, and -Score.
- [x] Core Algorithms: Linear Regression (), Decision Tree, Logistic Regression Sigmoid (), Naive Bayes, KNN ( tie behavior), and Neural Networks.
- [x] Cost Optimization: MSE Cost Function and simultaneous Gradient Descent update .