Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Machine Learning

Authors
Affiliations
ZHAW School of Engineering
ZHAW School of Engineering

Summary and Key Takeaways

Core Principles

  1. Generalization: The ultimate goal is to create models that perform well on unseen data, not just the training data.

  2. Bias-Variance Tradeoff: Every model makes a tradeoff between underfitting (high bias) and overfitting (high variance).

  3. No Free Lunch: No single algorithm works best for all problems. Choose based on your data and problem characteristics.

  4. Feature Engineering: The quality of your features often matters more than the choice of algorithm.

  5. Evaluation: Always use proper evaluation techniques (train-test split, cross-validation) to assess model performance.

Practical Skills Acquired

  • Data preprocessing and cleaning

  • Exploratory data analysis and visualization

  • Feature engineering and selection

  • Model selection and hyperparameter tuning

  • Supervised learning (classification and regression)

  • Unsupervised learning (clustering, dimensionality reduction)

  • Neural networks and deep learning

  • Model evaluation and interpretation

  • Python programming with ML libraries (numpy, pandas, scikit-learn, tensorflow/keras)

Python Libraries Used

LibraryPurposeKey Functions/Classes
numpyNumerical computingarray, linspace, random, etc.
pandasData manipulationDataFrame, Series, read_csv, etc.
matplotlibVisualizationpyplot, figure, scatter, plot, etc.
seabornStatistical visualizationheatmap, boxplot, pairplot, etc.
scikit-learnMachine learningAll ML algorithms, preprocessing, metrics
tensorflow/kerasDeep learningSequential, Dense, Conv2D, etc.
librosaAudio processingload, stft, mfcc, etc.

Quick Reference

Common Preprocessing Steps

Common Hyperparameter Tuning

Output
Best parameters: {'max_depth': None, 'min_samples_split': 2, 'n_estimators': 50}
Best score: 1.0000
Loading...

Common Model Evaluation

Output
Accuracy: 1.0000
Precision: 1.0000
Recall: 1.0000
F1: 1.0000
Confusion Matrix:
[[99  0]
 [ 0 55]]
Classification Report:
              precision    recall  f1-score   support

           0       1.00      1.00      1.00        99
           1       1.00      1.00      1.00        55

    accuracy                           1.00       154
   macro avg       1.00      1.00      1.00       154
weighted avg       1.00      1.00      1.00       154

MSE: 0.0000
MAE: 0.0000
R²: 1.0000

Introduction to Machine Learning

Educational Objectives

  • Basic, high-level understanding of what machine learning is

  • Understand the three main ML paradigms with examples

  • Data preparation and visualization techniques

  • Identify different data types and their characteristics

  • Perform data consolidation, preprocessing, and cleaning

  • Create effective data visualizations

Key Concepts

ML Paradigms

Supervised Learning

Data: (x,y)(x, y) where xx is input, yy is label Goal: Learn function to map x→yx \rightarrow y Example: Classifying apples vs. oranges

Unsupervised Learning

Data: xx (no labels) Goal: Learn underlying structure in data Example: Grouping similar items together

Reinforcement Learning

Data: State-action pairs Goal: Maximize future rewards over time Example: Learning to navigate an environment

Data Types

TypeDescriptionExample
NumericalContinuous or discrete numbersAge, temperature
CategoricalFinite set of categoriesColor, gender
OrdinalCategories with orderRating (1-5 stars)
TextNatural languageProduct reviews
ImagePixel arraysPhotographs
AudioSound waveformsSpeech recordings

Data Preprocessing Pipeline

Practical Example: Data Visualization

<Figure size 1000x600 with 1 Axes>
<Figure size 1200x800 with 2 Axes>

Supervised Learning & k-Nearest Neighbors

Educational Objectives

  • Address supervised ML problems: outline approach and name main concepts

  • Understand and explain the kNN algorithm and its advantages/disadvantages

  • Remember and explain most frequently used distance measures

  • Remember and explain prevalent performance measures for ML evaluation

Key Concepts

k-Nearest Neighbors Algorithm

kNN is a simple, instance-based learning algorithm:

  1. Store all training data

  2. Calculate distance between new point and all training points

  3. Find k nearest neighbors

  4. Predict based on majority vote (classification) or average (regression)

Distance metrics:Euclidean: d(x,y)=∑i=1n(xi−yi)2Manhattan: d(x,y)=∑i=1n∣xi−yi∣Minkowski: d(x,y)=(∑i=1n∣xi−yi∣p)1/p\text{Distance metrics:}\\ \text{Euclidean: } d(x, y) = \sqrt{\sum_{i=1}^{n} (x_i - y_i)^2}\\ \text{Manhattan: } d(x, y) = \sum_{i=1}^{n} |x_i - y_i|\\ \text{Minkowski: } d(x, y) = \left(\sum_{i=1}^{n} |x_i - y_i|^p\right)^{1/p}

Choosing k

  • Small k: More flexible, can overfit, sensitive to noise

  • Large k: More stable, can underfit, smoother decision boundaries

  • Optimal k: Found via cross-validation

Distance Measures

MeasureFormulaWhen to Use
Euclidean∑(xi−yi)2\sqrt{\sum (x_i - y_i)^2}General purpose
Manhattan∑∣xi−yi∣\sum | x_i - y_i|High-dimensional data
Cosine1−x⋅y∣x∣∣y∣1 - \frac{x \cdot y}{|x| |y|}Text data
HammingCount of differing positionsCategorical data

Performance Measures

Classification Metrics
  • Accuracy: TP+TNTP+TN+FP+FN\frac{TP + TN}{TP + TN + FP + FN}

  • Precision: TPTP+FP\frac{TP}{TP + FP} (How many selected are correct?)

  • Recall: TPTP+FN\frac{TP}{TP + FN} (How many actual positives found?)

  • F1 Score: 2×Precision×RecallPrecision+Recall2 \times \frac{Precision \times Recall}{Precision + Recall}

  • Confusion Matrix: Visualizes TP, TN, FP, FN

Regression Metrics
  • MSE: Mean Squared Error - sensitive to outliers

  • RMSE: Root Mean Squared Error - same units as target

  • MAE: Mean Absolute Error - robust to outliers

  • R²: Coefficient of determination - explains variance

Accuracy: 14.5000
Precision: 0.6667
Recall: 0.5833
F1: 0.6222

Practical Example: kNN Implementation

Output
Accuracy: 0.6948
              precision    recall  f1-score   support

           0       0.75      0.80      0.77        99
           1       0.58      0.51      0.54        55

    accuracy                           0.69       154
   macro avg       0.66      0.65      0.66       154
weighted avg       0.69      0.69      0.69       154

Best k: 11

Model Selection, Bias-Variance Tradeoff & Regularization

Educational Objectives

  • Understand the No Free Lunch theorem and Ockham’s Razor

  • Explain the influence of bias and variance on model performance

  • Explain loss minimization with stochastic gradient descent (SGD)

  • Use sound experimental setup to select model parameters, evaluate models, and choose among models

Key Concepts

Bias-Variance Tradeoff

Generalization Error=Bias2+Variance+Irreducible Error\text{Generalization Error} = \text{Bias}^2 + \text{Variance} + \text{Irreducible Error}

Regularization Techniques

TechniqueFormulaEffect
Lasso (L1)λ∑∣wi∣\lambda \sum |w_i |Feature selection, sparse weights
Ridge (L2)λ∑wi2\lambda \sum w_i^2Prevents large weights
Elastic Netλ1∑∣wi∣+λ2∑wi2\lambda_1 \sum |w_i| + \lambda_2 \sum w_i^2Combines L1 and L2

Model Selection, Bias-Variance Tradeoff & Regularization

Educational Objectives

  • Understand the No Free Lunch theorem and Ockham’s Razor

  • Explain the influence of bias and variance on model performance

  • Explain loss minimization with stochastic gradient descent (SGD)

  • Use sound experimental setup to select model parameters, evaluate models, and choose among models

Key Concepts

Bias-Variance Tradeoff

Generalization Error=Bias2+Variance+Irreducible Error\text{Generalization Error} = \text{Bias}^2 + \text{Variance} + \text{Irreducible Error}

Regularization Techniques

TechniqueFormulaEffect
Lasso (L1)λ∑∣wi∣\lambda \sum |w_i |Feature selection, sparse weights
Ridge (L2)λ∑wi2\lambda \sum w_i^2Prevents large weights
Elastic Netλ1∑∣wi∣+λ2∑wi2\lambda_1 \sum |w_i| + \lambda_2 \sum w_i^2Combines L1 and L2

Model Evaluation

Notebook Cell
Train-Test Split
K-Fold Cross-Validation
Mean CV Accuracy: 0.7643 (+/- 0.0488)
Learning Curves
<Figure size 1000x600 with 1 Axes>

Stochastic Gradient Descent (SGD)

Update rule: wt+1=wt−η∇L(wt)\text{Update rule: } w_{t+1} = w_t - \eta \nabla L(w_t)
  • η:=\eta := learning rate

  • ∇L(wt):=\nabla L(w_t) := gradient of loss function at wtw_t

Feature Engineering

Educational Objectives

  • Use EDA, data preparation, and cleaning as necessary steps before ML projects

  • Generate features using transformations (binning, interaction features)

  • Explain four approaches for feature selection

  • Generate features from text data (BoW, tf-idf, n-grams)

  • Identify important features for audio data: STFT and MFCC

Key Concepts

Feature Engineering Pipeline

Data Cleaning

<Axes: title={'center': 'After'}, ylabel='Insulin'>
<Figure size 1200x500 with 2 Axes>

Feature Generation Techniques

Numerical Features
  • Binning: Convert continuous to categorical

  • Polynomial: x,x2,x3x, x^2, x^3 for non-linear relationships

  • Interaction: x1×x2x_1 \times x_2 for feature combinations

  • Log Transform: log⁡(x)\log(x) for skewed distributions

  • Scaling: Standardize or normalize features

Categorical Features
  • One-Hot Encoding: Create binary columns for each category

  • Label Encoding: Convert categories to integers

  • Target Encoding: Replace categories with target mean

  • Frequency Encoding: Replace with frequency of category

Text Feature Extraction

Bag of Words (BoW)
  • Counts word occurrences

  • Ignores grammar and word order

  • Simple and effective baseline

TF-IDF
  • Term Frequency-Inverse Document Frequency

  • Weights words by importance

  • Rare words get higher weights

Audio Feature Extraction

STFT (Short-Time Fourier Transform)
  • Converts audio to time-frequency representation

  • Captures frequency content over time

  • Useful for speech and music analysis

MFCC (Mel-Frequency Cepstral Coefficients)
  • Represents spectral envelope of sound

  • Mimics human auditory system

  • State-of-the-art for speech recognition

Output
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Cell In[37], line 4
      1 import librosa
      2 
      3 # Load audio file
----> 4 y, sr = librosa.load('machine-learning/0_george_1.wav', sr=22050)
      5 
      6 # Extract STFT
      7 stft = librosa.stft(y, n_fft=2048, hop_length=512)

File ~/Development/marbetschar/marco.betschart.name/.venv/lib/python3.12/site-packages/lazy_loader/__init__.py:79, in attach.<locals>.__getattr__(name)
     77 submod_path = f"{package_name}.{attr_to_modules[name]}"
     78 submod = importlib.import_module(submod_path)
---> 79 attr = getattr(submod, name)
     81 # If the attribute lives in a file (module) with the same
     82 # name as the attribute, ensure that the attribute and *not*
     83 # the module is accessible on the package.
     84 if name == attr_to_modules[name]:

File ~/Development/marbetschar/marco.betschart.name/.venv/lib/python3.12/site-packages/lazy_loader/__init__.py:78, in attach.<locals>.__getattr__(name)
     76 elif name in attr_to_modules:
     77     submod_path = f"{package_name}.{attr_to_modules[name]}"
---> 78     submod = importlib.import_module(submod_path)
     79     attr = getattr(submod, name)
     81     # If the attribute lives in a file (module) with the same
     82     # name as the attribute, ensure that the attribute and *not*
     83     # the module is accessible on the package.

File /opt/homebrew/Cellar/python@3.12/3.12.10_1/Frameworks/Python.framework/Versions/3.12/lib/python3.12/importlib/__init__.py:90, in import_module(name, package)
     88             break
     89         level += 1
---> 90 return _bootstrap._gcd_import(name[level:], package, level)

File <frozen importlib._bootstrap>:1387, in _gcd_import(name, package, level)

File <frozen importlib._bootstrap>:1360, in _find_and_load(name, import_)

File <frozen importlib._bootstrap>:1334, in _find_and_load_unlocked(name, import_)

File <frozen importlib._bootstrap>:950, in _load_unlocked(spec)

File <frozen importlib._bootstrap_external>:999, in _LoaderBasics.exec_module(self, module)

File <frozen importlib._bootstrap>:488, in _call_with_frames_removed(f, *args, **kwds)

File ~/Development/marbetschar/marco.betschart.name/.venv/lib/python3.12/site-packages/librosa/core/audio.py:18
     15 import soxr
     16 import lazy_loader as lazy
---> 18 from numba import jit, stencil, guvectorize
     19 from .fft import get_fftlib
     20 from .convert import frames_to_samples, time_to_samples

File ~/Development/marbetschar/marco.betschart.name/.venv/lib/python3.12/site-packages/numba/__init__.py:59
     54             msg = ("Numba requires SciPy version 1.0 or greater. Got SciPy "
     55                    f"{scipy.__version__}.")
     56             raise ImportError(msg)
---> 59 _ensure_critical_deps()
     60 # END DO NOT MOVE
     61 # ---------------------- WARNING WARNING WARNING ----------------------------
     64 from ._version import get_versions

File ~/Development/marbetschar/marco.betschart.name/.venv/lib/python3.12/site-packages/numba/__init__.py:45, in _ensure_critical_deps()
     42 if numpy_version > (2, 4):
     43     msg = (f"Numba needs NumPy 2.4 or less. Got NumPy "
     44            f"{numpy_version[0]}.{numpy_version[1]}.")
---> 45     raise ImportError(msg)
     47 try:
     48     import scipy

ImportError: Numba needs NumPy 2.4 or less. Got NumPy 2.5.

Feature Selection Methods

MethodDescriptionWhen to Use
Variance ThresholdRemove features with low varianceInitial filtering
Univariate SelectionSelect best features based on statistical testsQuick feature reduction
RFERemove features iteratively based on model weightsModel-based selection
Model-based RankingUse feature importance from modelsTree-based models

Linear Models & Logistic Regression

Educational Objectives

  • Understand probability theory fundamentals (random variables, distributions)

  • Design loss functions using maximum likelihood and negative log-likelihood

  • Implement logistic regression for binary classification

  • Understand neuron structure and activation functions

Key Concepts

Probability Theory Basics

E[X]=∑xP(X=x) (discrete),∫xfX(x)dx (continuous) Var(X)=E[(X−E[X])2]=E[X2]−E[X]2E[X] = \sum x P(X = x) \text{ (discrete)}, \quad \int x f_X(x) dx \text{ (continuous)}\ Var(X) = E[(X - E[X])^2] = E[X^2] - E[X]^2
Bayes’ Theorem
P(A∣B)=P(B∣A)P(A)P(B)P(A|B) = \frac{P(B|A) P(A)}{P(B)}

Fundamental for Bayesian approaches to ML

Common Distributions
  • Bernoulli: Binary outcomes (p)

  • Gaussian: Continuous, symmetric (μ, σ²)

  • Multinomial: Multiple categories

  • Poisson: Count data (λ)

Loss Function Design

Maximum Likelihood Estimation (MLE)
L(θ)=P(X∣θ)=∏i=1nP(xi∣θ) ℓ(θ)=∑i=1nlog⁡P(xi∣θ) θ^=arg⁡max⁡θℓ(θ)L(\theta) = P(X | \theta) = \prod_{i=1}^n P(x_i | \theta)\ \ell(\theta) = \sum_{i=1}^n \log P(x_i | \theta)\ \hat{\theta} = \arg\max_{\theta} \ell(\theta)
Negative Log-Likelihood (NLL)
NLL=−ℓ(θ)=−∑i=1nlog⁡P(xi∣θ)\text{NLL} = -\ell(\theta) = -\sum_{i=1}^n \log P(x_i | \theta)

Logistic Regression

Sigmoid Function
σ(z)=11+e−z,z=w0+w1x1+⋯+wdxd\sigma(z) = \frac{1}{1 + e^{-z}}, \quad z = w_0 + w_1 x_1 + \dots + w_d x_d
Binary Cross-Entropy Loss
BCE=−1N∑i=1N[yilog⁡(y^i)+(1−yi)log⁡(1−y^i)]\text{BCE} = -\frac{1}{N} \sum_{i=1}^N \left[ y_i \log(\hat{y}_i) + (1 - y_i) \log(1 - \hat{y}_i) \right]
Implementation
Accuracy: 0.7468
Precision: 0.6379
Recall: 0.6727
F1 Score: 0.6549
array([[78, 21], [18, 37]])

Neural Networks & Deep Learning

Educational Objectives

  • Understand neural network architectures (shallow and deep)

  • Explain activation functions (ReLU, sigmoid, softmax)

  • Understand loss functions (MSE, cross-entropy)

  • Implement training with gradient descent and backpropagation

  • Apply optimization techniques (momentum, adaptive learning rates)

  • Implement CNNs for image processing

  • Apply regularization (L1/L2, dropout) and hyperparameter tuning

Key Concepts

Neural Network Architecture

Activation Functions

ReLU

Function: f(x)=max⁡(0,x)f(x) = \max(0, x) Pros: Solves vanishing gradient, computationally efficient Cons: Dies for negative inputs

Sigmoid

Function: f(x)=11+e−xf(x) = \frac{1}{1 + e^{-x}} Pros: Outputs between 0 and 1 Cons: Vanishing gradients

Softmax

Function: f(xi)=exi∑jexjf(x_i) = \frac{e^{x_i}}{\sum_j e^{x_j}} Use: Multi-class classification output Property: Outputs sum to 1

Loss Functions

Loss FunctionFormulaUse Case
MSE1n∑(yi−y^i)2\frac{1}{n}\sum (y_i - \hat{y}_i)^2Regression
Binary Cross-Entropy−∑[yilog⁡(y^i)+(1−yi)log⁡(1−y^i)]-\sum [y_i \log(\hat{y}_i) + (1-y_i)\log(1-\hat{y}_i)]Binary classification
Categorical Cross-Entropy−∑yilog⁡(y^i)-\sum y_i \log(\hat{y}_i)Multi-class classification

Backpropagation

  1. Forward pass: Compute predictions and loss

  2. Backward pass: Compute gradients using chain rule

  3. Update weights: Adjust weights using gradients

Optimization Techniques

Standard SGD

Update: wt+1=wt−η∇L(wt)w_{t+1} = w_t - \eta \nabla L(w_t)

SGD with Momentum

Update: vt+1=μvt−η∇L(wt)v_{t+1} = \mu v_t - \eta \nabla L(w_t) wt+1=wt+vt+1w_{t+1} = w_t + v_{t+1}

AdaGrad

Adaptive learning rates for each parameter

Adam

Combines momentum and adaptive learning rates

Regularization Techniques

L1/L2 Regularization
  • L1: λ∑∣wi∣\lambda \sum |w_i| - Encourages sparsity

  • L2: λ∑wi2\lambda \sum w_i^2 - Prevents large weights

  • Elastic Net: Combination of both

Dropout

Randomly deactivate neurons during training Prevents co-adaptation of neurons Typical rate: 0.2-0.5 for hidden layers

Practical Example: Neural Network with Keras

Epoch 1/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 1s 5ms/step - accuracy: 0.6075 - loss: 0.7251 - val_accuracy: 0.3571 - val_loss: 3.6762
Epoch 2/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - accuracy: 0.6922 - loss: 0.6318 - val_accuracy: 0.3571 - val_loss: 2.7727
Epoch 3/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - accuracy: 0.6922 - loss: 0.6022 - val_accuracy: 0.3571 - val_loss: 2.0603
Epoch 4/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - accuracy: 0.7362 - loss: 0.5714 - val_accuracy: 0.3636 - val_loss: 1.6119
Epoch 5/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - accuracy: 0.7182 - loss: 0.6093 - val_accuracy: 0.4026 - val_loss: 1.3522
Epoch 6/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - accuracy: 0.7410 - loss: 0.5509 - val_accuracy: 0.4740 - val_loss: 1.1482
Epoch 7/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7264 - loss: 0.5644 - val_accuracy: 0.5065 - val_loss: 0.9677
Epoch 8/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7476 - loss: 0.5292 - val_accuracy: 0.5844 - val_loss: 0.8118
Epoch 9/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7313 - loss: 0.5377 - val_accuracy: 0.6558 - val_loss: 0.7464
Epoch 10/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7524 - loss: 0.5107 - val_accuracy: 0.6753 - val_loss: 0.7077
Epoch 11/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7508 - loss: 0.5157 - val_accuracy: 0.7013 - val_loss: 0.6539
Epoch 12/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7394 - loss: 0.5104 - val_accuracy: 0.6818 - val_loss: 0.6117
Epoch 13/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7443 - loss: 0.5396 - val_accuracy: 0.6818 - val_loss: 0.5923
Epoch 14/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7476 - loss: 0.5272 - val_accuracy: 0.7143 - val_loss: 0.5663
Epoch 15/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7378 - loss: 0.5084 - val_accuracy: 0.7338 - val_loss: 0.5535
Epoch 16/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7524 - loss: 0.5020 - val_accuracy: 0.7338 - val_loss: 0.5504
Epoch 17/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7524 - loss: 0.5342 - val_accuracy: 0.7468 - val_loss: 0.5392
Epoch 18/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7736 - loss: 0.4804 - val_accuracy: 0.7532 - val_loss: 0.5321
Epoch 19/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7557 - loss: 0.4875 - val_accuracy: 0.7727 - val_loss: 0.5296
Epoch 20/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7524 - loss: 0.4988 - val_accuracy: 0.7662 - val_loss: 0.5310
Epoch 21/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7638 - loss: 0.4951 - val_accuracy: 0.7662 - val_loss: 0.5362
Epoch 22/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7492 - loss: 0.4789 - val_accuracy: 0.7662 - val_loss: 0.5332
Epoch 23/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7736 - loss: 0.4801 - val_accuracy: 0.7597 - val_loss: 0.5457
Epoch 24/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7459 - loss: 0.4987 - val_accuracy: 0.7662 - val_loss: 0.5500
Epoch 25/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7638 - loss: 0.4763 - val_accuracy: 0.7727 - val_loss: 0.5362
Epoch 26/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7492 - loss: 0.4857 - val_accuracy: 0.7792 - val_loss: 0.5280
Epoch 27/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7655 - loss: 0.4602 - val_accuracy: 0.7532 - val_loss: 0.5337
Epoch 28/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7280 - loss: 0.4937 - val_accuracy: 0.7403 - val_loss: 0.5364
Epoch 29/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7524 - loss: 0.5068 - val_accuracy: 0.7597 - val_loss: 0.5356
Epoch 30/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7720 - loss: 0.4679 - val_accuracy: 0.7597 - val_loss: 0.5278
Epoch 31/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7508 - loss: 0.4952 - val_accuracy: 0.7468 - val_loss: 0.5424
Epoch 32/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7427 - loss: 0.5075 - val_accuracy: 0.7338 - val_loss: 0.5455
Epoch 33/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7752 - loss: 0.4666 - val_accuracy: 0.7662 - val_loss: 0.5353
Epoch 34/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7687 - loss: 0.4610 - val_accuracy: 0.7662 - val_loss: 0.5360
Epoch 35/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7785 - loss: 0.4688 - val_accuracy: 0.7597 - val_loss: 0.5303
Epoch 36/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7785 - loss: 0.4726 - val_accuracy: 0.7532 - val_loss: 0.5296
Epoch 37/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7655 - loss: 0.4675 - val_accuracy: 0.7403 - val_loss: 0.5431
Epoch 38/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7736 - loss: 0.4775 - val_accuracy: 0.7468 - val_loss: 0.5474
Epoch 39/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7606 - loss: 0.4761 - val_accuracy: 0.7273 - val_loss: 0.5553
Epoch 40/100
20/20 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - accuracy: 0.7557 - loss: 0.4660 - val_accuracy: 0.7532 - val_loss: 0.5432
<Figure size 1200x400 with 2 Axes>
5/5 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - accuracy: 0.7597 - loss: 0.5278
Test Accuracy: 0.7597

Convolutional Neural Networks (CNNs)

Educational Objectives

  • Understand convolution operations for image processing

  • Implement pooling layers (max pooling, average pooling)

  • Apply CNNs to classification, detection, and segmentation tasks

  • Design CNN architectures for various computer vision tasks

Key Concepts

CNN Architecture Components

Convolution Operation

(I∗K)(i,j)=∑m∑nI(i+m,j+n)K(m,n)(I * K)(i, j) = \sum_m \sum_n I(i+m, j+n) K(m, n)
  • Kernel size: Typically 3x3, 5x5, 7x7

  • Stride: Step size of kernel (usually 1)

  • Padding: ‘same’ or ‘valid’

  • Number of filters: Determines output depth

Pooling Operations

Max Pooling

Takes maximum value in each window Preserves most prominent features Reduces spatial dimensions

Average Pooling

Takes average value in each window Smoother than max pooling Less sensitive to outliers

Practical Example: CNN for Fashion MNIST

Epoch 1/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 9s 20ms/step - accuracy: 0.7201 - loss: 0.7927 - val_accuracy: 0.5803 - val_loss: 1.3395
Epoch 2/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 7s 19ms/step - accuracy: 0.8252 - loss: 0.4829 - val_accuracy: 0.8673 - val_loss: 0.3565
Epoch 3/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 7s 19ms/step - accuracy: 0.8514 - loss: 0.4158 - val_accuracy: 0.8881 - val_loss: 0.3069
Epoch 4/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 7s 19ms/step - accuracy: 0.8632 - loss: 0.3791 - val_accuracy: 0.8914 - val_loss: 0.2920
Epoch 5/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 7s 20ms/step - accuracy: 0.8726 - loss: 0.3526 - val_accuracy: 0.8910 - val_loss: 0.2916
Epoch 6/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 20ms/step - accuracy: 0.8782 - loss: 0.3383 - val_accuracy: 0.8879 - val_loss: 0.2958
Epoch 7/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 7s 20ms/step - accuracy: 0.8833 - loss: 0.3216 - val_accuracy: 0.9041 - val_loss: 0.2614
Epoch 8/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 22ms/step - accuracy: 0.8867 - loss: 0.3089 - val_accuracy: 0.9098 - val_loss: 0.2435
Epoch 9/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 22ms/step - accuracy: 0.8892 - loss: 0.3019 - val_accuracy: 0.9066 - val_loss: 0.2487
Epoch 10/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 20ms/step - accuracy: 0.8923 - loss: 0.2962 - val_accuracy: 0.9129 - val_loss: 0.2365
Epoch 11/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 20ms/step - accuracy: 0.8966 - loss: 0.2874 - val_accuracy: 0.9133 - val_loss: 0.2377
Epoch 12/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 21ms/step - accuracy: 0.8987 - loss: 0.2824 - val_accuracy: 0.9113 - val_loss: 0.2344
Epoch 13/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 21ms/step - accuracy: 0.8990 - loss: 0.2769 - val_accuracy: 0.8921 - val_loss: 0.2973
Epoch 14/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 22ms/step - accuracy: 0.9016 - loss: 0.2724 - val_accuracy: 0.9198 - val_loss: 0.2170
Epoch 15/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 21ms/step - accuracy: 0.9023 - loss: 0.2705 - val_accuracy: 0.9165 - val_loss: 0.2259
Epoch 16/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 20ms/step - accuracy: 0.9050 - loss: 0.2632 - val_accuracy: 0.9161 - val_loss: 0.2277
Epoch 17/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 7s 20ms/step - accuracy: 0.9060 - loss: 0.2547 - val_accuracy: 0.9136 - val_loss: 0.2346
Epoch 18/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 20ms/step - accuracy: 0.9074 - loss: 0.2543 - val_accuracy: 0.9026 - val_loss: 0.2571
Epoch 19/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 7s 20ms/step - accuracy: 0.9072 - loss: 0.2539 - val_accuracy: 0.9218 - val_loss: 0.2127
Epoch 20/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 7s 20ms/step - accuracy: 0.9087 - loss: 0.2501 - val_accuracy: 0.9051 - val_loss: 0.2560
Epoch 21/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 7s 20ms/step - accuracy: 0.9100 - loss: 0.2447 - val_accuracy: 0.9229 - val_loss: 0.2107
Epoch 22/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 20ms/step - accuracy: 0.9121 - loss: 0.2446 - val_accuracy: 0.9243 - val_loss: 0.2059
Epoch 23/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 21ms/step - accuracy: 0.9109 - loss: 0.2457 - val_accuracy: 0.9261 - val_loss: 0.2060
Epoch 24/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 22ms/step - accuracy: 0.9124 - loss: 0.2398 - val_accuracy: 0.9258 - val_loss: 0.2024
Epoch 25/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 20ms/step - accuracy: 0.9132 - loss: 0.2390 - val_accuracy: 0.9251 - val_loss: 0.2032
Epoch 26/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 21ms/step - accuracy: 0.9136 - loss: 0.2349 - val_accuracy: 0.9107 - val_loss: 0.2338
Epoch 27/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 20ms/step - accuracy: 0.9155 - loss: 0.2332 - val_accuracy: 0.9246 - val_loss: 0.2028
Epoch 28/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 20ms/step - accuracy: 0.9151 - loss: 0.2330 - val_accuracy: 0.9277 - val_loss: 0.2027
Epoch 29/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 21ms/step - accuracy: 0.9160 - loss: 0.2314 - val_accuracy: 0.9186 - val_loss: 0.2185
Epoch 30/30
375/375 ━━━━━━━━━━━━━━━━━━━━ 8s 21ms/step - accuracy: 0.9163 - loss: 0.2294 - val_accuracy: 0.9302 - val_loss: 0.1939
Test loss: 0.2153
Test accuracy: 0.9226

Support Vector Machines (SVM)

Educational Objectives

  • Understand the SVM method in detail

  • Explain progression from maximal margin classifier to SVM

  • Explain the workings of C and γ parameters

  • Use SVM successfully on tutorial examples, including parameter grid search

  • Write down and explain the primal loss function of SVC

  • Apply the kernel trick for non-linearly separable classes

  • Understand Mercer Theorem and Representer Theorem

Key Concepts

SVM Evolution

Linear SVM

For linearly separable data, SVM finds the hyperplane that maximizes the margin:

Hyperplane: wTx+b=0,Margin: 2∥w∥\text{Hyperplane: } w^T x + b = 0, \quad \text{Margin: } \frac{2}{\|w\|}

Subject to: yi(wTxi+b)≥1y_i (w^T x_i + b) \geq 1 for all ii

Soft Margin SVM

Allows some misclassifications to handle non-separable data:

Minimize: 12∥w∥2+C∑i=1nξi,Subject to: yi(wTxi+b)≥1−ξi,ξi≥0\text{Minimize: } \frac{1}{2} \|w\|^2 + C \sum_{i=1}^n \xi_i, \quad \text{Subject to: } y_i (w^T x_i + b) \geq 1 - \xi_i, \xi_i \geq 0

Where:

  • CC = Regularization parameter

  • ξi\xi_i = Slack variables

Kernel Trick

Enables SVM to handle non-linear decision boundaries:

K(xi,xj)=ϕ(xi)Tϕ(xj)K(x_i, x_j) = \phi(x_i)^T \phi(x_j)

Common kernel functions:

KernelFunctionWhen to Use
LinearK(xi,xj)=xiTxjK(x_i, x_j) = x_i^T x_jLinearly separable data
PolynomialK(xi,xj)=(γxiTxj+r)dK(x_i, x_j) = (\gamma x_i^T x_j + r)^dPolynomial relationships
RBF/GaussianK(xi,xj)=exp⁡(−γ∣xi−xj∣2)K(x_i, x_j) = \exp(-\gamma |x_i - x_j|^2)General non-linear problems

Practical Example: SVM with scikit-learn

Accuracy: 0.7338
              precision    recall  f1-score   support

           0       0.77      0.83      0.80        99
           1       0.65      0.56      0.60        55

    accuracy                           0.73       154
   macro avg       0.71      0.70      0.70       154
weighted avg       0.73      0.73      0.73       154

Number of support vectors: [182 177]
Best parameters: {'C': 100, 'gamma': 0.001, 'kernel': 'rbf'}
Best CV score: 0.7720

Gaussian Processes

Educational Objectives

  • Apply Bayesian learning (Bayes’ theorem, Bayesian Regression, Bayes classifier)

  • Explain difference between maximum likelihood and Bayesian posterior estimation

  • Understand properties of Gaussian distributions (conditional, marginal, product, sum)

  • Understand Gaussian Process as a generalization of multivariate Gaussian distribution

  • Construct appropriate kernel functions for regression with GP

  • Sample functions from a Gaussian process and fit functions to data

Key Concepts

Bayesian Learning

Maximum Likelihood

Approach: Find parameters that maximize likelihood of observed data Formula: θ^MLE=arg⁡max⁡θP(X∣θ)\hat{\theta}_{MLE} = \arg\max_{\theta} P(X | \theta) Property: Point estimate, no uncertainty quantification

Bayesian Posterior

Approach: Compute probability distribution over parameters given data Formula: P(θ∣X)=P(X∣θ)P(θ)P(X)P(\theta | X) = \frac{P(X | \theta) P(\theta)}{P(X)} Property: Full distribution, quantifies uncertainty

Gaussian Distribution

N(x∣μ,σ2)=12πσ2exp⁡(−(x−μ)22σ2)\mathcal{N}(x | \mu, \sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)

Properties:

  • Marginalization: Any subset of a jointly Gaussian distribution is also Gaussian

  • Conditioning: Conditioning a Gaussian on some variables results in another Gaussian

  • Sum: Linear combination of Gaussians is Gaussian

Gaussian Process

A Gaussian Process (GP) is a collection of random variables, any finite number of which have a (multivariate) Gaussian distribution.

f:X→R∼GP(m(x),k(x,x′))f: X \rightarrow \mathbb{R} \sim \mathcal{GP}(m(x), k(x, x'))

Where:

  • m(x)m(x) = Mean function

  • k(x,x′)k(x, x') = Covariance function (kernel)

Common Kernel Functions

KernelFormulaProperties
RBFk(x,x′)=exp⁡(−∣x−x′∣22ℓ2)k(x, x') = \exp\left(-\frac{|x - x'|^2}{2\ell^2}\right)Smooth, infinitely differentiable
Lineark(x,x′)=xTx′k(x, x') = x^T x'Linear functions
Polynomialk(x,x′)=(xTx′+c)dk(x, x') = (x^T x' + c)^dPolynomial functions

Practical Example: Gaussian Process Regression

<Figure size 1000x600 with 1 Axes>
<Figure size 1000x600 with 1 Axes>

Dimensionality Reduction

Educational Objectives

  • Understand the curse of dimensionality

  • Explain the manifold hypothesis

  • Implement Principal Component Analysis (PCA)

  • Understand Kernel PCA for non-linear extensions

  • Apply manifold learning techniques (MDS, LLE, Isomap, t-SNE)

Key Concepts

Curse of Dimensionality

Manifold Hypothesis

Principal Component Analysis (PCA)

PCA finds orthogonal directions (principal components) that maximize variance. Steps:

  1. Center the data: Xcentered=X−XˉX_{centered} = X - \bar{X}

  2. Compute covariance matrix: Σ=1nXcenteredTXcentered\Sigma = \frac{1}{n} X_{centered}^T X_{centered}

  3. Eigendecomposition: Σ=VΛVT\Sigma = V \Lambda V^T

  4. Select top kk eigenvectors

Practical Example: PCA for Visualization

<Figure size 1000x800 with 2 Axes>
Explained variance ratio: [0.26179749 0.21640127]
Total explained variance: 0.4782

Kernel PCA

<Figure size 1000x800 with 2 Axes>

Manifold Learning Techniques

Multidimensional Scaling (MDS)
  • Preserves pairwise distances

  • Linear technique

  • Good for visualization

t-SNE
  • Preserves local structure

  • Non-linear technique

  • Excellent for visualization

  • Computationally expensive

Local Linear Embedding (LLE)
  • Preserves local linear relationships

  • Non-linear technique

  • Good for manifold learning

Isomap
  • Preserves geodesic distances

  • Non-linear technique

  • Uses neighborhood graph

<Figure size 1000x800 with 2 Axes>

Cluster Analysis

Educational Objectives

  • Understand different clustering paradigms

  • Implement and interpret hierarchical clustering

  • Use the elbow method to determine optimal number of clusters

  • Apply partitioning methods like k-Means

  • Understand density-based clustering (DBSCAN)

  • Evaluate clustering results

Key Concepts

Types of Clustering

Partitioning
  • k-Means: Partitions data into k clusters

  • k-Medoids: Uses actual data points as centers

  • Fuzzy c-Means: Soft clustering (probabilistic)

Hierarchical
  • Agglomerative: Bottom-up

  • Divisive: Top-down

  • Dendrogram: Visual representation

Density-Based
  • DBSCAN: Density-based spatial clustering

  • OPTICS: Similar to DBSCAN but more robust

  • HDBSCAN: Hierarchical DBSCAN

k-Means Algorithm

  1. Initialize k cluster centers randomly

  2. Assign each point to nearest cluster center

  3. Recalculate cluster centers as mean of assigned points

  4. Repeat steps 2-3 until convergence

Objective: Minimize WCSS=∑i=1k∑x∈Ci∥x−μi∥2\text{Objective: Minimize WCSS} = \sum_{i=1}^k \sum_{x \in C_i} \|x - \mu_i\|^2

Practical Example: k-Means Clustering

<Figure size 1000x800 with 1 Axes>
Silhouette Score: 0.7569
Davies-Bouldin Score: 0.3560
<Figure size 800x400 with 1 Axes>

Hierarchical Clustering Example

<Figure size 1200x600 with 1 Axes>

DBSCAN Example

<Figure size 1000x800 with 1 Axes>
Number of clusters: 2
Number of noise points: 0

Gaussian Mixture Models & Expectation-Maximization

Educational Objectives

  • Understand Gaussian Mixture Models (GMMs)

  • Implement the Expectation-Maximization (EM) algorithm

  • Understand soft clustering vs. hard clustering

  • Apply GMMs to real-world data

  • Understand the relationship between GMMs and k-Means

Key Concepts

Gaussian Mixture Model

A probabilistic model that assumes data is generated from a mixture of several Gaussian distributions:

P(x)=∑k=1KπkN(x∣μk,Σk)P(x) = \sum_{k=1}^K \pi_k \mathcal{N}(x | \mu_k, \Sigma_k)

Where:

  • πk\pi_k = Mixing coefficient, ∑πk=1\sum \pi_k = 1

  • μk\mu_k = Mean of component k

  • Σk\Sigma_k = Covariance matrix of component k

Expectation-Maximization (EM) Algorithm

  1. E-step (Expectation): Compute posterior probabilities (responsibilities)

  2. M-step (Maximization): Update parameters using current responsibilities

  3. Repeat until convergence

E-step: γnk=πkN(xn∣μk,Σk)∑j=1KπjN(xn∣μj,Σj)\text{E-step: } \gamma_{nk} = \frac{\pi_k \mathcal{N}(x_n | \mu_k, \Sigma_k)}{\sum_{j=1}^K \pi_j \mathcal{N}(x_n | \mu_j, \Sigma_j)}

GMM vs. k-Means

AspectGMMk-Means
ClusteringSoft (probabilistic)Hard (deterministic)
Cluster ShapeEllipticalSpherical
CovarianceCan be differentSame (identity)
ProbabilisticYesNo

Practical Example: GMM with scikit-learn

<Figure size 1000x800 with 2 Axes>
Means:
[[-2.26099844  6.07059032]
 [-6.83235214 -6.83045757]]
Covariances:
[[[ 31.61453403 -12.1886063 ]
  [-12.1886063    9.63288295]]

 [[  1.011053    -0.06122604]
  [ -0.06122604   0.79622858]]]
Weights:
[0.75000001 0.24999999]
AIC: 3181.6956036449124, BIC: 3222.4372108661305
<Figure size 800x400 with 1 Axes>

Reinforcement Learning

Educational Objectives

  • Define finite Markov Decision Process (MDP) and Markov Reward Process (MRP)

  • Understand value iteration and Q-learning algorithms

  • Explain the difference between on-policy and off-policy learning

  • Explain the difference between value iteration and policy iteration

  • Understand the trade-off between exploitation and exploration

Key Concepts

Markov Decision Process (MDP)

A framework for modeling decision-making situations:

MDP=(S,A,P,R,γ)\text{MDP} = (S, A, P, R, \gamma)

Where:

  • SS = Set of states

  • AA = Set of actions

  • P(s′∣s,a)P(s'|s,a) = Transition probability

  • R(s,a,s′)R(s,a,s') = Reward function

  • γ\gamma = Discount factor (0≤γ≤10 \leq \gamma \leq 1)

Markov Property

P(st+1∣st,at,st−1,at−1,...)=P(st+1∣st,at)P(s_{t+1} | s_t, a_t, s_{t-1}, a_{t-1}, ...) = P(s_{t+1} | s_t, a_t)

Value Functions

Vπ(s)=Eπ[∑k=0∞γkRt+k+1∣St=s]Qπ(s,a)=Eπ[∑k=0∞γkRt+k+1∣St=s,At=a]V^\pi(s) = \mathbb{E}_\pi \left[ \sum_{k=0}^\infty \gamma^k R_{t+k+1} \mid S_t = s \right]\\ Q^\pi(s,a) = \mathbb{E}_\pi \left[ \sum_{k=0}^\infty \gamma^k R_{t+k+1} \mid S_t = s, A_t = a \right]

Bellman Equation

Vπ(s)=Eπ[Rt+1+γVπ(St+1)∣St=s]Qπ(s,a)=Eπ[Rt+1+γQπ(St+1,At+1)∣St=s,At=a]V^\pi(s) = \mathbb{E}_\pi \left[ R_{t+1} + \gamma V^\pi(S_{t+1}) \mid S_t = s \right]\\ Q^\pi(s,a) = \mathbb{E}_\pi \left[ R_{t+1} + \gamma Q^\pi(S_{t+1}, A_{t+1}) \mid S_t = s, A_t = a \right]

Optimal Policy

π∗(s)=arg⁡max⁡aQ∗(s,a),where Q∗(s,a)=max⁡πQπ(s,a)\pi^*(s) = \arg\max_a Q^*(s,a), \quad \text{where } Q^*(s,a) = \max_\pi Q^\pi(s,a)

Dynamic Programming Methods

Value Iteration
Vk+1(s)=max⁡aE[Rt+1+γVk(St+1)∣St=s,At=a]V_{k+1}(s) = \max_a \mathbb{E} \left[ R_{t+1} + \gamma V_k(S_{t+1}) \mid S_t = s, A_t = a \right]
Policy Iteration
  1. Policy Evaluation: Compute VπV^\pi for current policy

  2. Policy Improvement: Update policy to be greedy with respect to VπV^\pi

Temporal Difference Learning

TD(0): V(St)←V(St)+α[Rt+1+γV(St+1)−V(St)]\text{TD(0): } V(S_t) \leftarrow V(S_t) + \alpha \left[ R_{t+1} + \gamma V(S_{t+1}) - V(S_t) \right]

Q-Learning

Q(St,At)←Q(St,At)+α[Rt+1+γmax⁡aQ(St+1,a)−Q(St,At)]Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha \left[ R_{t+1} + \gamma \max_{a} Q(S_{t+1}, a) - Q(S_t, A_t) \right]

Exploration vs. Exploitation

Exploration
  • Try different actions to discover better strategies

  • Needed to find optimal policy

  • Can lead to suboptimal short-term rewards

Exploitation
  • Use known best action to maximize immediate reward

  • Can miss better long-term strategies

  • Suboptimal in the long run if overused

Common exploration strategies:

  • ε-greedy: Choose random action with probability ε

  • Decaying ε-greedy: ε decreases over time

  • Upper Confidence Bound (UCB): Balance exploration and exploitation

  • Thompson Sampling: Probabilistic approach based on uncertainty

On-Policy vs. Off-Policy

AspectOn-PolicyOff-Policy
DefinitionLearns about and improves the same policyLearns about one policy while following another
ExampleSARSAQ-Learning
AdvantageDirectly learns the policy being followedCan learn optimal policy while following exploratory policy
DisadvantageMust balance exploration/exploitationMore complex, can be unstable

Practical Example: Q-Learning for Frozen Lake

Final reward: 0.0

Ensemble Methods

Educational Objectives

  • Understand ensemble learning principles

  • Implement bagging methods (e.g., Random Forest)

  • Implement boosting methods (e.g., AdaBoost, Gradient Boosting)

  • Understand the bias-variance tradeoff in ensemble methods

  • Apply ensemble methods to real-world problems

Key Concepts

Ensemble Learning

Combining multiple models to improve performance:

Types of Ensembles

Bagging (Bootstrap Aggregating)
  • Principle: Reduce variance by averaging multiple models

  • Method: Train models on different bootstrap samples

  • Example: Random Forest

  • Effect: Reduces variance, prevents overfitting

Boosting
  • Principle: Reduce bias by sequentially correcting errors

  • Method: Train models sequentially, each focusing on previous errors

  • Examples: AdaBoost, Gradient Boosting, XGBoost

  • Effect: Reduces bias, improves accuracy

Gini Impurity

Gini Impurity is a measure of node purity used in decision trees (CART algorithm). It quantifies the probability of misclassifying a randomly selected sample in a node if it were labeled according to the distribution of classes in the node.

For a node with KK classes, where pip_i is the proportion of class ii:

Gini=1−∑i=1Kpi2\text{Gini} = 1 - \sum_{i=1}^{K} p_i^2
  • Range: 0 (perfectly pure) to 1−1K1 - \frac{1}{K} (maximally impure)

  • Interpretation: Lower values indicate higher purity

0.276923076923077

Random Forest

An ensemble of decision trees trained on bootstrap samples with feature subsampling:

  1. Create bootstrap samples (with replacement)

  2. For each sample, train a decision tree on a random subset of features

  3. Average predictions from all trees

Feature subsampling: m≈d for classification, m≈d/3 for regression\text{Feature subsampling: } m \approx \sqrt{d} \text{ for classification, } m \approx d/3 \text{ for regression}

Boosting Methods

AdaBoost
  • Idea: Give more weight to misclassified samples

  • Algorithm: Sequentially train models, reweighting data

  • Weight Update: Increase weights for misclassified samples

Gradient Boosting
  • Idea: Fit new models to residual errors

  • Algorithm: Each new model corrects errors of previous ensemble

  • Loss: Minimizes loss function (e.g., MSE, log-loss)

Practical Example: Random Forest

Random Forest Accuracy: 0.7208
<Figure size 1000x600 with 1 Axes>

Gradient Boosting Example

Gradient Boosting Accuracy: 0.7468
<Figure size 1000x600 with 1 Axes>

AdaBoost Example

AdaBoost Accuracy: 0.7403

Generative AI and Wrap-Up

Educational Objectives

  • Understand the landscape of generative AI

  • Explain different generative modeling approaches

  • Understand applications and limitations of generative models

  • Reflect on the future of machine learning

  • Integrate knowledge from all course topics

Key Concepts

Generative AI Overview

Generative AI models learn to generate new data that resembles the training data:

Generative Adversarial Networks (GANs)
  • Idea: Two neural networks compete (generator vs. discriminator)

  • Training: Generator tries to fool discriminator

  • Applications: Image generation, style transfer

Variational Autoencoders (VAEs)
  • Idea: Learn probability distribution of data

  • Training: Maximize likelihood of data

  • Applications: Image generation, anomaly detection

Large Language Models (LLMs)
  • Idea: Predict next token in sequence

  • Training: Self-supervised on vast text data

  • Applications: Text generation, translation, coding

Generative Model Types

ModelApproachTrainingApplications
GANAdversarialMinimax gameImages, audio
VAEProbabilisticMaximum likelihoodImages, data generation
AutoregressiveSequentialNext token predictionText, audio, video
DiffusionIterative denoisingNoise removalImages, audio
  • Scale: Models continue to grow in size and capability

  • Efficiency: More efficient architectures and training methods

  • Multimodality: Models that understand multiple data types

  • Alignment: Ensuring models behave as intended (safety, ethics)

  • Interpretability: Understanding model decisions

  • Automation: AutoML and hyperparameter optimization