Docsity

Summary notes about unsupervised machine learning techniques, Sintesi del corso di Machine learning

Toggle sidebar
bg1
Contents
1 LESSON 1 - INTRO 3
1.1 ULTASK:MANIFOLDLEARNING .......................................... 3
1.2 ULTASK:ESTIMATIONOFp(x)............................................ 3
1.3 ULTASK:CLUSTERING................................................ 3
2 LESSON 2 - PCA 4
2.1 Properties........................................................ 4
2.2 Derivation........................................................ 4
2.3 Deciden°dimensionstokeep ............................................ 4
3 LESSON 4 - Multi-Dimensional Scaling (MDS) 5
3.0.1 2.2 Types of Multi-Dimensional Scaling (MDS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.1 3.WorkingwithDistances............................................... 5
3.1.1 3.3 Conditions for a Metric Distance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.1.2 3.1Advantages................................................. 5
3.2 4.TypesofDistances ................................................. 5
3.2.1 4.1MetricDistances.............................................. 5
3.2.2 4.2Non-MetricDistances........................................... 5
3.2.3 4.3 Distances for Binary Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
4 UML 6 - PCA vs MDS 6
4.1 Recovering set of coordinates Yfrom Euclidean Distances θ........................... 6
4.2 Recovering Coordinates (Y) from Gram Matrix (G) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.3 MDS: Minimizing Differences (Stress) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.4 Approximating Geodesic Distances (Neighbor Graph) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5 Lesson 7 - KERNEL PCA 7
5.1 Kerneltrick ....................................................... 7
5.1.1 Typesofkernels ................................................ 7
5.2 KPCAalgorithm .................................................... 7
6 UML 9 - Dimensionality Reduction Methods 8
6.1 2.DiffusionMaps ................................................... 8
6.2 3.SketchMap(Non-MetricMDS) .......................................... 8
6.2.1 4.1. t-Distributed Stochastic Neighbor Embedding (t-SNE) . . . . . . . . . . . . . . . . . . . . . . . . 8
6.2.2 4.2. UMAP (Uniform Manifold Approximation and Projection) . . . . . . . . . . . . . . . . . . . . . . . 8
7 Autoencoders 9
8 LESSON 12 - Variational Autoencoders (VAEs) - to fix 10
8.1 IntroductionandGoals ................................................ 10
9 LESSON 13 - INTRINSIC DIMENSION - NEW 12
9.1 Nearest Neighbor-Based Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
9.2 The 2NN Method (Two Nearest Neighbors) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
9.2.1 Deriving D from P(µ): ............................................. 12
9.3 5. Other Intrinsic Dimension Estimation Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
10 LESSON 15 - ESTIMATING PDFs - to fix 13
10.0.12.1.ParametricMethods ........................................... 13
10.0.2 2.2. Non-Parametric Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
10.1 3. Parametric Density Estimation: Gaussian Mixture Model (GMM) . . . . . . . . . . . . . . . . . . . . . . . . 13
10.2 5. Non-Parametric Density Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
10.2.15.1.Histograms ................................................ 13
10.2.25.2.ParzenWindows ............................................. 14
10.2.3 5.3. Kernel Density Estimation (KDE) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
10.2.4 K-Nearest Neighbor (K-NN) Density Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
11 LESSON 18 - Clustering and Feature Selection - to fix 15
11.1 Clustering Methods: Objectives & Output Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
11.2 K-Means Clustering Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

Anteprima parziale del testo

Scarica Summary notes about unsupervised machine learning techniques e più Sintesi del corso in PDF di Machine learning solo su Docsity!

Contents

  • 1 LESSON 1 - INTRO
    • 1.1 UL TASK: MANIFOLD LEARNING
    • 1.2 UL TASK: ESTIMATION OF p(x)
    • 1.3 UL TASK: CLUSTERING
  • 2 LESSON 2 - PCA
    • 2.1 Properties
    • 2.2 Derivation
    • 2.3 Decide n° dimensions to keep
  • 3 LESSON 4 - Multi-Dimensional Scaling (MDS) - 3.0.1 2.2 Types of Multi-Dimensional Scaling (MDS)
    • 3.1 3. Working with Distances
      • 3.1.1 3.3 Conditions for a Metric Distance
      • 3.1.2 3.1 Advantages
    • 3.2 4. Types of Distances
      • 3.2.1 4.1 Metric Distances
      • 3.2.2 4.2 Non-Metric Distances
      • 3.2.3 4.3 Distances for Binary Features
  • 4 UML 6 - PCA vs MDS
    • 4.1 Recovering set of coordinates Y from Euclidean Distances θ
    • 4.2 Recovering Coordinates (Y) from Gram Matrix (G)
    • 4.3 MDS: Minimizing Differences (Stress)
    • 4.4 Approximating Geodesic Distances (Neighbor Graph)
  • 5 Lesson 7 - KERNEL PCA
    • 5.1 Kernel trick
      • 5.1.1 Types of kernels
    • 5.2 KPCA algorithm
  • 6 UML 9 - Dimensionality Reduction Methods
    • 6.1 2. Diffusion Maps
    • 6.2 3. Sketch Map (Non-Metric MDS)
      • 6.2.1 4.1. t-Distributed Stochastic Neighbor Embedding (t-SNE)
      • 6.2.2 4.2. UMAP (Uniform Manifold Approximation and Projection)
  • 7 Autoencoders
  • 8 LESSON 12 - Variational Autoencoders (VAEs) - to fix
    • 8.1 Introduction and Goals
  • 9 LESSON 13 - INTRINSIC DIMENSION - NEW
    • 9.1 Nearest Neighbor-Based Methods
    • 9.2 The 2NN Method (Two Nearest Neighbors)
      • 9.2.1 Deriving D from P ( μ ):
    • 9.3 5. Other Intrinsic Dimension Estimation Methods
  • 10 LESSON 15 - ESTIMATING PDFs - to fix - 10.0.1 2.1. Parametric Methods - 10.0.2 2.2. Non-Parametric Methods
    • 10.1 3. Parametric Density Estimation: Gaussian Mixture Model (GMM)
    • 10.2 5. Non-Parametric Density Estimation
      • 10.2.1 5.1. Histograms
      • 10.2.2 5.2. Parzen Windows
      • 10.2.3 5.3. Kernel Density Estimation (KDE)
      • 10.2.4 K-Nearest Neighbor (K-NN) Density Estimation
  • 11 LESSON 18 - Clustering and Feature Selection - to fix
    • 11.1 Clustering Methods: Objectives & Output Types
    • 11.2 K-Means Clustering Algorithm
  • 12 LESSON 20 correct numeration - Clustering Limitations and Advanced Techniques
    • 12.1 Kernel K-means
      • 12.1.1 Distance as a Function of Assignations
    • 12.2 Fuzzy C-means
  • 13 LESSON 21 - HIERARCHICAL CLUSTERING
    • 13.1 Divisive hierarchical clustering - top down
    • 13.2 Agglomerative hierarchical clustering - bottom up
    • 13.3 Single Linkage Distance
    • 13.4 Complete Linkage Distance
    • 13.5 Group Average Distance
    • 13.6 Centroid Linkage Distance
    • 13.7 Ward’s Linkage Distance
    • 13.8 Example of divisive algorithm - (with 5 elements A, B, C, D, E)
  • 14 LESSON 22 - Affinity Propagation Clustering Algorithm
    • 14.1 Overview
    • 14.2 Messages Exchanged
      • 14.2.1 Responsibility (R(i,k))
      • 14.2.2 Availability (A(i,k))
    • 14.3 The Affinity Propagation Algorithm Steps
    • 14.4 Post-Iteration Process (Cluster Formation)
    • 14.5 Disadvantages of Affinity Propagation
  • 15 LESSON 23 - to fix
    • 15.1 Spectral Clustering
    • 15.2 Constructing the Similarity Graph (Weight Matrix, W)
    • 15.3 Optimal Graph Cuts
    • 15.4 Normalizing cuts (addressing cluster size, incorporated into loss function)
    • 15.5 Matrices Involved in Spectral Clustering
    • 15.6 Relaxation of the Spectral Clustering Problem
    • 15.7 Unnormalized Spectral Clustering Algorithm - Minimizing RatioCut
    • 15.8 Normalized Spectral Clustering Algorithm - Minimizing Normalized Cut
  • 16 LESSON 24 DBSCAN (Density-Based Spatial Clustering of Applications with Noise) - 16.0.1 1.2. Advantages - 16.0.2 1.3. Limitations (Problems)
  • 17 LESSON 25 - Comprehensive Notes on Density-Based Clustering Algorithms
    • 17.1 2. Density Peaks Clustering (DP)
      • 17.1.1 2.2. Key Definitions & Steps
      • 17.1.2 2.3. Halo Points
    • 17.2 3. Mean Shift Clustering
    • 17.3 5. Hierarchical Density-Based Clustering (HDBScan & DPA)
      • 17.3.1 5.3. DPA (Density Peaks Advanced)
  • 18 LESSON 26 - Clustering Validation: Assessing Meaningful Clusters
    • 18.1 2. Internal Validation Metrics
      • 18.1.1 2.1. F-ratio Test
      • 18.1.2 2.2. Silhouette Coefficient
    • 18.2 3. External Validation Metrics
      • 18.2.1 3.1. Rand Index (RI)
      • 18.2.2 3.2. Normalized Mutual Information (NMI)

2 LESSON 2 - PCA

Linear dimensionality reduction technique. Finds a new coordinate system capturing max amount of information (variance) using fewest dimensions possible. Constrained optimization problem.

2.1 Properties

Centering: subtract mean from each data point. This ensures the 1 st^ component describes shape of data

Orthogonality: every PC must be ⊥ (orthogonal) to all others to ensure no redundant info is captured.

Linearity: assumes data lies on flat manifold, if not it will overestimate n° dimensions required to represent it

Ordering: PC are ordered by descending variance.

No scale invariance: features with larger scales can dominate. If features are already in same units and their differences are significant, normalizing might lead to loss of information.

2.2 Derivation

Let S be the covariance matrix of centered data

S =

N

∑^ N

n =

xnxTn

Find vector u (direction of 1 st^ PC) s.t. variance of projected data is maximized. Projected variance is given by uT^ Su.

To prevent u from growing to ∞, constrain it to be a unit vector uT^ u = 1

To find max under a constraint, define Lagrangian multiplier :

L ( u, λ ) = uT^ Su − λ ( uT^ Su − 1)

Taking derivative wrt u and setting to zero:

∂L ∂u

= 2 Su − 2 λu = 0 ⇒ Su = λu

This is an eigenvalue problem:

  • u must be an eigenvector of covariance matrix S
  • variance along that direction is exactly the eigenvalue λ
  • to maximize variance, choose eigenvector with largest eigenvalue

2.3 Decide n° dimensions to keep

Scree plot: graph showing magnitude of each eigenvalue in descending order

Elbow method: pt where eigenvalues stop dropping significantly. Dimensions after elbow = noise.

Explained variance ratio:

t =

∑ d ∑ Di^ λ^1 i λi

∑kept λ all λ Tells the amount of variance being preserved

3 LESSON 4 - Multi-Dimensional Scaling (MDS)

Objective: reproduce distances from original ”ambient space” into lower-dimensional ”projected space.” Goal: the two sets of distance matrices should be ideally identical to avoid information loss. Stress: defined as error or difference between these two sets of distances, serving as a loss function.

3.0.1 2.2 Types of Multi-Dimensional Scaling (MDS) Classical MDS Uses a square loss in the distance space. Equivalent to PCA if Euclidean distances are used in both original and projected spaces.

Metric MDS Preserves relative importance of distances. Less sensitive to outliers than Classical MDS.

Non-metric MDS Focuses on the relative order (rank) of neighbors. Uses a function to transform distances. Allows fine-tuning for specific problem types (i.e changing map size to fit data).

3.1 3. Working with Distances

Similarity: higher Distance: lower

values mean more similar

3.1.1 3.3 Conditions for a Metric Distance Non-negativity: d ( x, y ) ≥ 0 ∀ x, y, and d ( x, y ) = 0 iff x = y. (For similarities, s ( x, x ) = 1).

Symmetry: d ( x, y ) = d ( y, x )∀ x, y.

Triangle Inequality: d ( x, z ) ≤ d ( x, y ) + d ( y, z )∀ x, y, z. Critical condition.

3.1.2 3.1 Advantages

Non-numerical Data: Can map data without knowing exact coordinates. Visualization: Provides insights into data geometry and features. Pairwise Comparisons: (e.g., sequence alignment: count common letters to derive similarity).

3.2 4. Types of Distances

3.2.1 4.1 Metric Distances

  • Minkowski Distance: (

(| xi − yi | p ))(^1 /p ).

- p = 2: Euclidean (straight line). - p = 1: Manhattan (city block, sum of absolute differences, grid movement). - p = ∞: Chebyshev or Superior distance (max of absolute differences max (| xi − yi |))

  • Mahalanobis Distance: - Divides by variance to handle scale differences. - If features are correlated, squashes diagonal to measure true distance relative to data shape.

3.2.2 4.2 Non-Metric Distances

  • Cosine Similarity: focuses on direction (angle) between vectors. 1 = perfectly collinear, 0 = orthogonal.
  • Pearson Correlation: Measures the linear correlation between two sets of data.

3.2.3 4.3 Distances for Binary Features

Jaccard Similarity: Number of common features / Total number of features considered. Not a metric distance. Hamming Distance: Minimum number of changes needed to transform one data point into another. proper metric distance.

5 Lesson 7 - KERNEL PCA

Idea: expand original space into a higher-dimensional feature space where data becomes linearly separable.

Transformation example: ( x 1 , x 2 ) −MAP−−→ ϕ

x 1 ϕ 1 ,^

x 2 ϕ 2 ,^

x^21 + x^22 ϕ 3

Result: points originally in the center would be near the origin of ϕ 3 while outer points would have a higher ϕ 3 value, making them linearly separable.

5.1 Kernel trick

Sometimes data isn’t linearly separable or well represented in its original space. So, a feature map ϕ ( x ) is applied and sends each data point x into a higher dimensional feature space. Computing ϕ ( x ) explicitly can be very expensive/impossible, feature space could have ∞ dimensions.

Kernel function: Computes inner product without explicitly mapping x to ϕ ( x ). Operates directly on original inputs xi and xℓ^ mathematically giving the same result.

kiℓ = k ( xi, xℓ ) = ⟨ ϕi, ϕℓ ⟩

5.1.1 Types of kernels

Linear kiℓ = k ( xi, xℓ ) = xi, xℓ

⊤

Polynomial kiℓ = k ( xi^ − xℓ ) δ^ version 1 kiℓ = k ( xi^ − xℓ^ + 1) δ^ version 2 (More powerful)

Dimension expansion: the new feature space dimension can be significantly larger

Valid kernel for a function k ( i, l ) to be a valid kernel, resulting kernel matrix K must be: Symmetric: ki,l = kl,i Positive Semi-Definite: for any vector c:

i

l ciclki,l^ ≥^0. Satisfies Mercer’s theorem.

Mercer’s Theorem: if satisfied, there exists a feature map ϕ mapping data into a high-dimensional space such that kernel computes dot product in that space.

k ( i, l ) = ⟨ ϕ ( xi ) , ϕ ( xl )⟩

5.2 KPCA algorithm

  1. Map input x to a HD feature space ϕ ( x ) where data is linearly separable.
  2. To perform PCA in this new space, data must be centered:

ϕ^ ˜ i^ = ϕ ( xi )^1 N

∑^ N

k =

ϕ ( xk )

  1. Kernel trick: work with inner products (kernel matrix). ϕ ˜ cannot be computed directly (dimensions too high).

kil = ⟨ ϕi, ϕℓ ⟩

  1. Apply double centering formula.

k centered il = kil −

N

k

kik −

N

m

klm +

N^2

k,m

kkm

  1. Diagonalize k centered to find eigenvalues/eigenvectors
  2. Project data onto those eigenvectors.

6 UML 9 - Dimensionality Reduction Methods

6.1 2. Diffusion Maps

Uses diffusion distance (probabilistic approach penalizing travel through low-density regions, reflecting a more ”meaningful” distance on the manifold). Equivalent to MDS with diffusion distance.

Define Diffusion Kernel: Gaussian kernel k ( xi, xl ) = exp (−|| xi − xl ||^2 / (2 ∗ σ^2 )). σ : key hyperparameter, max distance for single jump between points, (scale of noise.)

Normalize Kernel: Apply diffusion normalization to transform it into a transition probability matrix. Represents probability of transitioning from one data point to another. Markov matrix (Markov chain process).

Spectral Decomposition: Analyze transition probability matrix.

Eigenvectors: representing new low-dimensional coordinates, similar to Kernel PCA. First eigenvector often corresponds to equilibrium population.

6.2 3. Sketch Map (Non-Metric MDS)

Stress (loss): function of sum of squared distance differences. Allows focusing on specific distances most important for reproduction, incorporating prior knowledge/biases.

Stress =

i

l ( wi^ ∗^ ( g ( δil )^ −^ g ( dil ))

wi Relative importance of point i. Can be set to 1 for all points if no specific importance is known. δil Distance between points i and l in the original highprojected low-dimensional space. dil g ( δ ) A complex function 1 − 2 ·

1 1+( δ/σ ) A

) B

  • σ : defines region of interest for distances. Distances δ ≤ σ are considered important for the loss function.
  • A, B : affect speed of function decrease for distances δ > σ , influencing how less important larger distances become. When properly parameterized, it can be extremely effective in dimensionality reduction. Parameter selection is non-trivial, requires significant domain knowledge/ experimentation. General Principle: designed for curved manifolds whose local structure is preserved by short distances.

Stochastic Embedding: Reproduce prb of being neighbors, maximize similarity bwn these prbs in embedding (original data) and projected space.

6.2.1 4.1. t-Distributed Stochastic Neighbor Embedding (t-SNE)

Probabilities in Embedding Space: PL | I =

exp

− ∥ xI^ − xL ∥

2 2 σ I^2

K ̸ = I exp

− ∥ xI^ − xK^ ∥

2 2 σ I^2

Uses a Gaussian function of distances. σI is point-dependent (different for each point I).

Symmetrization: PIL =

PL | I + PI | L

2 N

N : total points

Perplexity: σI = 2(

L ( PL | I^ log^2 ( PL | I^ ))). Effective n° of nearest neighbors to preserve. Non-linear equation.

Loss function: Kullback-Leibler divergence KL ( P || Q ) =

I

L ( PIL^ log (^

PIL QIL ))^

PIL :embedding space prbs QIL :projected space prbs Minimize this function to find optimal projected coordinates y.

Probabilities in Projected Space ( QIL ):

  • Gaussian (SNE): Causes ”over-crowding” where distant points overlap in low-D.
  • t-Distribution (t-SNE): degree 1 allow for better separation of dissimilar points.

QIL =

(1 + || yI − yL ||^2 )(−1) ∑ K ̸ = M (1 +^ || yK^ −^ yM^ || (^2) )(−1)) yI^ , yL^ Euclidean distances in projected space

  • Numerical minimization: requires initializing y coordinates randomly, leading to different results on each run.
  • Convergence: difficult for projected dimensions d > 2.
  • Loss of global structure: heavily focused on small distances, poor representation of global relationships.

6.2.2 4.2. UMAP (Uniform Manifold Approximation and Projection)

PIL definition: Uses a non-normalized exponential kernel PIL = exp

− max (0 , || xI σ^ − IxL ||− ρI^ )

Distances < ρI ≈ 0 (points are in same location), prevent excessive emphasis on very small distances.

σI determination: Found via a parameter k (number of neighbors of interest).

Symmetrization: PI | L = PI | L + PL | I − ( PI | L · PL | I )

QIL expression: designed for specific decay properties. QIL = (^) 1+ a ·|| yI^1 − yL || 2 b

Loss function: Uses cross-entropy like term explicitly penalizing not being neighbors when they should Loss =

IL PIL^ log^ ( PIL/QIL ) + (1^ −^ PIL )^ log^ (^1 − PIL/^1 − QIL )

Initialization: y coords initialized from graph Laplacian, ensure consistent results across runs, improve convergence.

8 LESSON 12 - Variational Autoencoders (VAEs) - to fix

8.1 Introduction and Goals

VAEs introduce variational inference to autoencoders. Two main approaches to VAEs:

  • Practical: Focus on applications.
  • Theoretical: Starting from original inference and mathematics.

Regularization of latent space

  • Necessary to make AEs generative
  • Done by placing a probability distribution (a prior) over the latent space. - This concentrates ”mass” around specific regions - Ex: prior is a std normal distribution. Latent representations would be constrained to cluster around zero. - Benefit: sampling a point from prior distribution has a high chance of corresponding to meaningful data when decoded, thus enabling generation.

VAE as a Generative Model

  • Deep Generative Models - Model the density (p(x)) of observed data (x), estimating the likelihood of each training point. - Generate data distributed as p(x) (i.e., generate meaningful samples). - Challenge: p(x) lives in a very high-dimensional space, making direct modeling impossible.
  • Latent Variable Models - Assumption: Data (x, observed) is generated from an unobserved random variable Z (latent variable). - Generative Process:

* Sample Z from a prior distribution p(Z).

* Generate X from a conditional distribution p(X|Z).

- Manifold hypothesis: Z lives in RM^ (much smaller dimension M), X lives in RD^ (much larger dimension D). - p(X|Z) acts as the decoder.

Probabilistic Decoder

  • Decoder fθ ( Z ) outputs parameters ( η ) for a probability distribution pϕ ( X | Z ).
  • Process: - Decoder ( fθ ) takes Z as input. - Outputs eta (parameters) in a parameter space (H). - These eta parameters define the output density pϕ ( X | Z ).
  • Model Choice: The type of output density pϕ depends on the data - Categorical Distribution: For integer pixel values (0-255 in images). Decoder outputs logits for each pixel. - Normal Distribution: For continuous data or normalized pixel values (e.g., 0-1). Decoder outputs mean and variance for each dimension of X. - Poisson/Negative Binomial: For count data.
  • p(Z): The prior distribution over the latent space. Typically chosen to be simple, like a standard normal distribution, for ease of sampling.

Learning Objective and Variational Inference

  • Intractability of Log-Likelihood - Goal: Learn the decoder parameters ( θ ). - Natural Objective: Maximize the log-likelihood of the data: logp ( X ). - Problem: logp ( X ) = log

p ( X | Z ) p ( Z ) dZ is intractable because the integral over the continuous latent space Z is unknown and hard to compute (due to high dimensionality and ”curse of dimensionality”).

* Monte Carlo approximation is usually ineffective due to very high variance.

  • Evidence Lower Bound (ELBO) - Solution: Variational Inference provides a lower bound for the intractable log-likelihood. - Key Idea: Introduce an approximating distribution q ( Z | X ) (called the variational posterior or inference model) to ap- proximate the true (intractable) posterior p(Z|X). - Derivation: Using Jensen’s inequality, the log-likelihood can be shown to be greater than or equal to the ELBO: logp ( X ) ≥ Eq [ logp ( X | Z )] − KL (q(Z|X)|| p ( Z )) - ELBO Components:

* Eq^ [ logp ( X | Z )]: Expected log-likelihood of data given latent variables (related to reconstruction loss). This term wants

q ( Z | X ) to place mass where p ( X | Z ) is high.

* KL (q(Z|X)|| p ( Z )): Kullback-Leibler (KL) divergence between the variational posterior^ q ( Z | X )^ and the prior^ p ( Z ). This

term acts as a regularization term, forcing q ( Z | X ) to be close to p ( Z ).

- Maximizing ELBO: implicitly maximize the log-likelihood and push q ( Z | X ) towards p(Z|X).

  • Role of Variational Posterior q ( Z | X ) - q ( Z | X ) is a parametric family (e.g., Gaussian) whose parameters are learned. - It’s designed to be an approximation of the true posterior p(Z|X), which is intractable. - Why tractable?:

* q ( Z | X )^ is a known, simple distribution.

* p(X|Z) (decoder) is parameterized by a neural network.

* p(Z) (prior) is a simple choice (e.g., standard normal).

Amortized Variational Inference (The Encoder)

  • Bridging Variational Inference and Neural Networks - Problem with standard VI: q ( Z | X ) would need to be estimated for each data point ( Xi ), which is computationally impossible for large datasets. - Kingma and Welling’s Key Idea (VAE): Use a neural network to ”amortize” the variational distribution.

* This means making^ q ( Z | X )^ dependent on the input X.

* Instead of estimating a separate q for each^ Xi , the network learns a function that outputs the parameters of q for

any given X.

  • Encoder’s Role - The neural network gϕ ( X ) acts as the encoder. - It takes X as input and outputs the parameters (k) of the variational posterior q ( Z | X ). - q ( Z | X ) is now a probabilistic encoder. - Example: If q ( Z | X ) is assumed to be a normal distribution, the encoder gϕ ( X ) outputs the mean (mu) and log-variance ( logσ^2 ) (often log-variance for numerical stability) for Z. - This makes the encoder itself probabilistic: given X, output is a distribution q ( Z | X ).
  • Practical Implementation (Gaussian) - Typically, q ( Z | X ) is chosen as a normal distribution. - The encoder gϕ ( X ) outputs μ ( X ) and σ^2 ( X ) (or logσ^2 ( X )). - From this q ( Z | X ), a latent code Z can be sampled. - This sampled Z is then passed to the decoder p(X|Z) to reconstruct X.

The Reparameterization Trick

  • Problem with Sampling Node - The ELBO requires taking gradients with respect to the encoder parameters (phi) and decoder parameters (theta). - The first term of the ELBO Eq [ logp ( X | Z )] involves an expectation over Z sampled from q ( Z | X ). - The parameters phi (of the encoder) determine q ( Z | X ), meaning the sampling operation for Z is a stochastic node dependent on phi. - Standard backpropagation (autograd) cannot compute gradients through this stochastic sampling step.
  • Solution - The reparameterization trick rewrites the sampling process to separate the stochasticity from the parameters. - For a Gaussian q ( Z | X ) = N ( μ ( X ), σ^2 ( X )) : Z = μ ( X )+ σ ( X )∗ ϵ where ϵ is sampled from a standard normal distribution N (0 , 1). - Benefit: epsilon is independent of phi. Now, Z is a deterministic function of μ ( X ), sigma(X), and epsilon. - Gradients can now flow deterministically through μ ( X ) and sigma(X) (outputs of the encoder) back to the encoder parameters phi.
  • VAE Loss Components - The ELBO is maximized, which is equivalent to minimizing the negative ELBO, commonly referred to as the VAE loss. - Loss = − Eq [ logp ( X | Z )] + KL ( q ( Z | X )|| p ( Z ))

* Term 1: Reconstruction Loss (− Eq^ [ logp ( X | Z )]): Measures how well the decoder reconstructs the input data.

· This is the equivalent of the reconstruction error in standard AEs. · If p ( X | Z ) is Gaussian, this term simplifies to a mean squared error (MSE) like term.

* Term 2: Regularization Loss (KL( q ( Z | X )^ || p(Z))): Forces the learned latent distribution^ q ( Z | X )^ to be close to the

chosen prior p(Z). · This is typically computed in closed form when both q and p are Gaussians.

- Relationship to Autoencoder Loss:

* With specific assumptions (encoder only parametrizes mean, fixed variance, decoder outputs mean, fixed variance),

the VAE reconstruction term resembles a ”noisy version” of the autoencoder’s MSE loss.

* The VAE loss is essentially the standard autoencoder reconstruction loss plus the KL divergence term for latent space

regularization.

Challenges in VAEs

  • Posterior Collapse - Problem: The KL divergence term can become zero for each X if q ( Z | X ) collapses to p ( Z ). This means the encoder ignores the input X and always outputs a q ( Z | X ) identical to the prior. - Consequence: The latent space becomes effectively useless for encoding information about X, and the decoder only learns to generate samples from the prior, leading to poor reconstruction quality. - Theoretical Problem: If q ( Z | X ) perfectly equals the standard normal prior, the KL term is minimized to zero.
  • Hole Problem / Mismatch between Prior and Aggregated Posterior - Aggregated Variational Posterior: This is the mixture distribution formed by averaging all individual q ( Z | X ) distributions from the training data (e.g., ( (^) N^1 ) ∗

i q ( Z | Xi )).

- Problem: There can be a mismatch between the chosen prior p ( Z ) and the aggregated variational posterior.

* For example, if the aggregated posterior has multiple clusters (e.g., for different digits in MNIST), but the prior is a

single standard normal, there will be ”holes” in the prior’s high-density regions that are not covered by data samples.

- Consequence: If sampling from the prior, one might pick points that don’t correspond to any training data distribution, leading to unrealistic generations.

10 LESSON 15 - ESTIMATING PDFs - to fix

10.0.1 2.1. Parametric Methods Assume functional form for density and learn its parameters of this by fitting data. Requires less data for good estimates. Doesn’t need to learn functional form. If assumed functional form is wrong, method will not perform well or will have problems. Functional form assumption induces biases that cannot be fixed by adding more data.

10.0.2 2.2. Non-Parametric Methods

Make no assumption about the functional form of the density. Can adapt to complex densities. Need more data to achieve good estimates. Often involve hyperparameters that balance bias and variance.

10.1 3. Parametric Density Estimation: Gaussian Mixture Model (GMM)

Functional form: approximates the real density P ( X ) as a sum of K Gaussian functions:

ρ ( x ) = Σ i = 1 K^ [ πi · N ( x | μi, Σ i )]

πi : Weight for the i-th Gaussian component N ( x | μi, Σ i ) Gaussian function with mean μi and covariance Σ i

Parameters: model learns πi, μi, and Σ i for each of the K Gaussian components.

Assumptions: Number of components K is known (or needs to be inferred).

Normalization condition: sum of weights Σ iπi = 1 to ensure ρ ( x ) is a valid PDF.

Likelihood Function: For a dataset { x 1 , ..., xN }, likelihood is: L = πn = 1 N^ [ ρ ( xn )] Taking the logarithm: log ( L ) = Σ Nn =1 log (Σ Ki =1[ πi · N ( xn | μi, Σ i )]).

Optimization challenge: For K > 1 , likelihood function is analytically non-optimizable due to log of a sum.

Solution: EM algorithm. Iterative numerical method, finds parameters maximizing likelihood.

Initialization: Initialize parameters ( πi, μi, Σ i ) to some values.

Expectation: Compute posterior probability (responsibility) γ ( zni ) that data point xn was generated by i th Gaussian component

γ ( zni ) = πi · N ( xn | μi, Σ i ) Σ Kj =1 πj · N ( xn | μj , Σ j )

Maximization : Update the parameters using the computed responsibilities to maximize the likelihood

Effective n° points for component i: Ni = Σ n = 1 N^ γ ( zni ) New weights: πinew = Ni/N New means: μinew = Σ Nn =1[ γ ( zni ) · xn ] /Ni New covariances (1D): Σ^2 inew = Σ Nn =1[ γ ( zni ) · ( xn − μinew )^2 ] /Ni

10.2 5. Non-Parametric Density Estimation

10.2.1 5.1. Histograms

  • Define K disjoint intervals (bins) Ij with a constant bin width h (for simplicity).
  • Count the number of occurrences Nj of data points xi within each interval Ij.
  • The probability of a point belonging to interval Ij is P ( x ∈ Ij ) =

Ij P^ ( X ) dx.

  • This can be approximated by Nj /N (where N is total data points).
  • Using a rectangle approximation for the integral:

Ij P^ ( X ) dx^ ≈^ P^ ( xj^ )^ ·^ h^ (where^ xj^ =^ center of^ Ij^ ).

  • Equating approximations: P ( xj ) · h ≈ Nj /N.
  • PDF Estimate: P ( xj ) ≈ Nj / ( N · h ).
  • The integral of this estimate over all space

ρ ( x ) dx ≈ Σ P ( xj ) · h = Σ( Nj / ( N · h )) · h = Σ Nj /N = N/N = 1.

Error Analysis (Variance):

  • Nj (n° counts in a bin). Random variable following Binomial distribution B ( N, Pj )
  • Pj : true probability of x ∈ Ij.
  • Expected value E [ Nj ] = N · Pj.
  • Variance V ar [ Nj ] = N · Pj · (1 − Pj ).
  • If N is large and Pj is small, Nj can be approximated by a Poisson distribution with variance Nj ≈ N · Pj.

Curse of Dimensionality: In HD, most bins will be empty or contain very few points, leading to huge errors and useless estimates.

Bias-Variance Trade-off according to bin width (h):

Small: Low Bias: Can capture local variations in the PDF. High Variance: Many bins with few counts, leading to noisy estimates.

Large: ▲ B: smooth out local variations, assume uniform density over wide regions (might be false). Low Variance: More counts per bin, leading to more stable estimates.

Optimal: Friedman-Diaconis Rule h ≈ 2 IQR √ (^3) N

IQR (Interquartile Range): x 75 th − x 25 th percentile. Assumes properties of the underlying distribution to estimate h.

Problem: Even with fixed h, starting pt for 1 st^ bin needs to be chosen, introducing another hyperparameter.

10.2.2 5.2. Parzen Windows Avoids the ”starting point” issue of histograms. A ”small rectangle” (window function) of a specific width h is placed at the center of each data point. Overall PDF is the sum of these rectangle functions.

  • Each rectangle has height (^) N h^1 and area (^) N^1.
  • ρ ( x ) = (^) N h^1 · Σ Nn =1 [Rectangle( x − hx n )]

Superposition: Where rectangles overlap, their contributions are summed.

10.2.3 5.3. Kernel Density Estimation (KDE)

Generalization of Parzen Windows: replaces ”rectangle” function with a kernel function that integrates to 1 (

K ( u ) du = 1).

PDF Estimate: ρ ( x ) = (^) N h^1 · Σ Nn =

[

K ( x − hx n )

] (^) h :Bandwidth (aka smoothing parameter) K :Kernel function (Uniform/Rectangle, Gaussian).

Key Differences from GMM: the bandwidth h is a hyperparameter, not learned from data. Visualization: Places a kernel function with width h on top of each data point and sums them up.

Bias-Variance Trade-off (Bandwidth h):

Large: Smoother estimate (low variance, high bias). May over-smooth and miss fine details.

Small: Less smooth estimate (high variance, low bias). Can capture local details but may be noisy.

Optimal: Silverman’s Rule: h ≈ 0_._ 9 · min(Σ data, IQR/ 1_._ 34) · N −^ (^15)

  • Minimizes integrated mean squared error (IMSE) for Gaussian distribution.
  • Weakness: Assumes properties of underlying distribution, which might be false.

Cross-Validation: More robust

  • Hold-out: Divide data into XA and XB. Train KDE model on XA for different h values, evaluate its likelihood/ KL divergence on XB. Choose h minimizing divergence.
  • K-fold: Generalizes hold-out to multiple splits.

10.2.4 K-Nearest Neighbor (K-NN) Density Estimation

Can be derived from a likelihood function. Focuses on distances from a central point to its nearest neighbors. Assumes data points are randomly distributed (IID) according to a Poisson process. Volumes of spheres around the central point that enclose each successive nearest neighbor follow an exponential law. This holds for constant density.

Estimation Process:

  • Consider a central point L.
  • Identify K nearest neighbors.
  • Measure volume VKL enclosed by K-th nearest neighbor (sphere containing K points).
  • Estimate density ( ρ ) using Maximum Likelihood Estimation (MLE). - Likelihood function based on the exponential distribution of volumes. - Log-likelihood for K points: log ( L ) = K · log ( ρ ) − ρ · VKL - Deriving with respect to ρ and setting to zero yields: ρ = (^) VKKL.
  • Density is estimated as the number of points (K) divided by the volume ( VKL ) they occupy. - VKL is the volume of a hypersphere whose radius is the distance to the K-th nearest neighbor.

Error / Variance:

  • MLE allows calculating the Cramér-Rao lower bound for the error.
  • The variance of the estimate ( σ^2 ) is inversely proportional to K and ρ^2.
  • This implies more data points (larger K) lead to lower variance/error.
  • Crucial Caveat: This is only true under the assumption of constant density.

Bias-Variance Trade-off in K-NN:

  • Larger K: ▼ variance, ▲ likelihood of constant density assumption violation, leading to a biased estimate.
  • Optimal K: Difficult to choose, ideally provides the best compromise between bias and variance.

11.2 K-Means Clustering Algorithm

Centroid ( cL ): average coordinates of all data points belonging to a specific cluster L.

cL =

xi ∀ xi in cluster L Number of points in cluster L

Loss Function (Inertia): Measures intra-cluster dissimilarity (how compact clusters are around their centers). Loss =

(for k = 1 to K clusters)

(for each data point xi in cluster k ) (distance( xi, ck ))^2 Target: Find the partition that minimizes this loss.

Algorithm (K-Means): The problem of finding the global minimum of the loss is NP-hard; K-Means performs a local optimization.

  1. Initialization: Pick K initial centers (typically randomly chosen from data points).
  2. Iteration (Repeat until convergence):
  • (a) Designation (Assignment): Assign each data point to its nearest center. - This step minimizes the intra-cluster distance. - Generates a Voronoi partition of the space.
  • (b) Recomputation (Update): Recompute centroids for each cluster based on its newly assigned data points. - This step tends to maximize distances among centers, moving them to ”true” center of current cluster.

Sensitive to Initialization: Can get trapped in local minima of the loss function. Solutions:

  • Run K-Means several times with different random initializations and pick the run with the lowest loss.
  • K-Means++: Aims to pick initial centers more wisely. - Pick the first center purely randomly. - For subsequent centers (up to K):

* Compute the minimum distance (D) from each remaining data point to all already assigned centers.

* Pick next new center with probability^ ∝^ D

(^2) (favors points far from existing centers, ensuring better initial spread).

Choice of K (Number of Clusters): significant problem if goal is to identify real data partitions Solution: Scree Plot (Elbow Method)

  • Plot the loss (inertia) as a function of K (number of clusters).
  • Look for an ”elbow” point where decrease in loss becomes substantially less steep (flattens). This suggests that adding more clusters beyond this point provides diminishing returns in reducing within-cluster variance.
  • Requires running K-Means (multiple times to approximate global minima) for each K value.
  • K-Means is good at making partitions, but not inherently at identifying correct number of natural groups.

Sensitive to Outliers: these can shift centroid (mean), distorting cluster definition/partition. Solution: K-Medoids:

  • Medoid: data pt within cluster having min sum of distances to all other points in that cluster (analogous to median in HD).
  • Advantage: Medoids are actual data points, making them less susceptible to extreme outliers than means.

Only Works in Euclidean Spaces: Solution: K-Medoids works with distances, allows use of non-Euclidean metrics.

Only works for convex clusters: For non-convex, centroid might fall within another cluster. Solution: geodesic distance

12 LESSON 20 correct numeration - Clustering Limitations and Advanced Tech-

niques

12.1 Kernel K-means

Process:

    1. Initialize n centers.
    1. Iterate: Re-assign points based on distance in the feature space. Distances computed in a HD feature space (via kernel function) w/o explicitly transforming data. Note: There’s a distinction between the kernel itself and the Gram matrix. Double centering is involved.

12.1.1 Distance as a Function of Assignations The Euclidean distance squared can be expanded: || ϕi − ϕj ||^2 = ϕi − ϕi + ϕj · ϕj − 2 ϕiϕj = kii^ + kjj^ − 2 kij

This can be related to kernel functions (K). By substituting K values, distance can be expressed as a function of assignations and kernel output. This allows iteration in a ”feature space” to perform k-means.

12.2 Fuzzy C-means

Contrast with K-means:

  • K-means: - ”one-hot encoding” (hard assignments). - A point ϕi belongs entirely to one cluster cj. - Membership μip (e.g., (0, 0, 1, 0) implies full membership to the 3 rd^ cluster).
  • Fuzzy C-means: - ”fuzzy” membership values (soft assignments). - A point ϕi can belong to multiple clusters with varying degrees. - Membership μip (e.g., (0.1, 0.3, 0.6)). - Condition: The sum of memberships for any point across all clusters must be 1 (

μip = 1).

Objective Function: L =

i

j μ

f ij || xi^ −^ cj^ || (^2) f: Fuzzification parameter.

  • f = 1 recovers k-means (hard assignment).
  • f = 2 is frequently assumed.

Center Definition: cj =

i μ

f ij xi ∑ i μ

f ij

(weighted average of positions)

Algorithm: Similar to K-means.

    1. Initialize membership matrix U randomly.
    1. Iterate until convergence: - Calculate cluster centers ( cj ) using the weighted average formula. - Update membership values based on new centers distance, divided by distances to other centers.

14 LESSON 22 - Affinity Propagation Clustering Algorithm

14.1 Overview

Message passing algorithm (clustering based on data points communicating with each other iteratively). Determines exemplars (members of input set representative of clusters) Automatically defines # clusters (that consists of all elements sharing same exemplar).

14.2 Messages Exchanged

14.2.1 Responsibility (R(i,k)) Represents the accumulated evidence that sample k should be the exemplar for sample i. Update Formula: R ( i, k ) = S ( i, k ) − max k ′ (^) ̸= k [ S ( i, k ′) + A ( i, k ′)] Initial step (when all A values are 0): R ( i, k ) = S ( i, k ) − max k ′ (^) ̸= k ( S ( i, k ′))

14.2.2 Availability (A(i,k))

Reflects the accumulated evidence that sample i would choose sample k as its exemplar. Update formula: If i ̸= k : A ( i, k ) = min(0 , R ( k, k ) +

i ′^ ̸= i,k max(0 , R ( i

′ , k ))) else ∑ i ′!= k max(0 , R ( i

′ , k ))

14.3 The Affinity Propagation Algorithm Steps

Define Similarities (S):

  • Standard definition: S ( i, k ) = −|| xi − xk ||^2 (negative squared Euclidean distance). Allows for negative S.
  • S ( k, k ) (Preference): Similarity of a point with itself. This is a critical hyperparameter for the method. - Setting S ( k, k ) to min(max( SSikik^ ) ) results in fewmany clusters. - Default: median( Sik ). Initialization: Set all responsibility and availability values to zero. Iterate: Repeatedly update R ( i, k ) and A ( i, k ) using the formulas above. Termination:
  • The process stops when a pre-defined number of iterations (another hyperparameter) is reached.
  • Algorithm does not necessarily converge to a solution but evolves. Longer run = less clustering changes.
  • Message passing process can be extremely unstable, leading to huge changes in R and A in a single iteration.
  • This instability is usually mediated by a damping factor ( λ ), which is another hyperparameter.
  • r ( i, k ) t +1 = λ · r ( i, k ) t + (1 − λ ) · r ′( i, k ) t +
  • (where r ( i, k ) t is the previous value and r ′( i, k ) t +1 is the freshly calculated value).

14.4 Post-Iteration Process (Cluster Formation)

A point i is an exemplar if sum of its availability and responsibility is maximal for itself compared to all other points. i = arg max l ( Ail + Ril ). Points are then assigned to clusters using the exemplars.

14.5 Disadvantages of Affinity Propagation

Extreme hyperparameter dependence: results are highly sensitive to the chosen hyperparameters, especially Skk (the preference). Even small changes can drastically alter the clustering structure.

Preference for Convex Clusters: its standard similarity measure is typically defined based on Euclidean distance. This could potentially be mitigated by using different similarity measures (e.g., geodesic distance).

15 LESSON 23 - to fix

15.1 Spectral Clustering

Transform data points into an undirected weighted graph G ( V, E ).

  • Sil ≥ 0 : Edge weight (similarity) between points i and l.
  • Sil = Sli : Symmetric
  1. Use graph theory to find ”optimal” cuts.
  2. Identify clusters as the connected components after these cuts.

15.2 Constructing the Similarity Graph (Weight Matrix, W)

Choice of hyperparameters ( ε, k, σ ) is crucial and can dramatically alter the clustering results. Methods for obtaining W (can be combined,e.g., applying a similarity function only to k-NN connections).

Epsilon-ball graph: Connects vertices if they are within a given radius ε.

k-NN graph: Connects vertices to their k nearest neighbors. Requires symmetrization (e.g., Sij = Sji = 1 if i is a k-NN of j OR j is a k-NN of i ) since k-NN is not commutative.

Fully connected graphs (Clique): Every vertex is connected to every other vertex. Edge weights Sij are a function of the

distance dij between points i and j. Common function: Gaussian similarity Sij = e − d

(^2) ij/ 2 σ 2

15.3 Optimal Graph Cuts

A cut defines a partition ( C, C ′) in the graph.

  • cut ( C, C ′) =

i ∈ C,j ∈ C ′^ ( Sij^ ). Sums weights of edges connecting points in C to points in C’.

K-Way Cut: Generalization for K partitions ( C 1 , C 2 , ..., CK ).

  • K-Way Cut( C 1 , ..., CK ) = 12 ·

m =1→ K ( cut ( Cm, C ′ m )).

  • Minimization problem: - It does not account for the population/size of the clusters. - It tends to generate heavily unbalanced clusters (e.g., isolating a single point as a cluster)

15.4 Normalizing cuts (addressing cluster size, incorporated into loss function)

Ratio Cut: Size Measure: | Cm | (# vertices in cluster Cm ). Loss Function: RatioCut( C 1 , ..., CK ) =

m =1→ K (cut( Cm, C ′ m ) / | Cm |). Minimizing this ensures that smaller clusters (with smaller | Cm | in the denominator) contribute more to the loss if their cut value is high, discouraging heavily unbalanced partitions.

Normalized Cut: Degree of a point i: Sum of weights of all connections from point i. di =

j =1→ N ( Sij^ ). Volume of a cluster: Sum of degrees of all points within cluster Cm. V ol ( Cm ) =

i ∈ Cm ( di ). Loss Function: N Cut ( C 1 , ..., CK ) =

m =1→ K ( cut ( Cm, C ′ m ) /V ol ( Cm )). This measure considers both the number of points and their connectivity within the cluster.

15.5 Matrices Involved in Spectral Clustering

Weight: N x N symmetric matrix (N number of data points). Wij = Sij for i ̸= j. Wii = 0 (no self-loops).

Degree: N x N symmetric diagonal matrix. Dii = di (the degree of point i). Dij = 0 for i ̸= j.

Laplacian: L = D − W. Symmetric positive semi-definite. vT^ Lv = 12 ·

i,j ( Sij^ ( vi^ −^ vj^ )

(^2) ). Minimizing vT (^) Lv seeks vi values

that are similar for strongly connected nodes.

15.6 Relaxation of the Spectral Clustering Problem

Discrete cluster indicator variables are relaxed to continuous, real-valued vectors. For K clusters, this involves an N x K matrix H of indicator vectors. Minimizing RatioCut (K clusters) ≡ minimizing T race ( HT^ LH ) subject to HT^ H = I (orthogonality constraint). Minimizing NCut (K clusters) ≡ minimizing T race ( HT^ LH ) subject to HT^ DH = I. Discrete optimization transformed into generalized eigenvalue/vector problem. Columns of H = eigenvectors.

15.7 Unnormalized Spectral Clustering Algorithm - Minimizing RatioCut

Construct similarity matrix W and Laplacian L = D - W. Compute 1 st^ k eigenvectors of L corresponding to k smallest eigenvalues (exclude trivial ones associated to eigenvalue 0). Discretize: form N × k mx H where each column is one of the computed eigenvectors. Perform k-means clustering on rows of H to assign each data point to a cluster.

15.8 Normalized Spectral Clustering Algorithm - Minimizing Normalized Cut

Construct Similarity Matrix W and Degree Matrix D. Compute the Symmetric Normalized Laplacian Lsym = D (−^ (^12) ) LD (−^ (^12) ) ( L = D − W ). Compute the first k eigenvectors of Lsym corresponding to the k smallest eigenvalues. Let these eigenvectors form the columns of an N x k matrix T. Discretize: Perform k-means clustering on the rows of T to assign each data point to a cluster.