Unsupervised learning

Lecture 4 · Machine Learning for ICE · University of Klagenfurt, 2023

Nunzio Alexandro Letizia

This lecture

Lecture 4 of 8

No labels any more, only the inputs \mathbf{x}_i:

  1. K-means: find groups in the data
  2. Principal component analysis: find the few directions that matter

From Machine Learning for ICE at the University of Klagenfurt, first taught in 2022: this is the 2023 edition, so some of it may be a little dated. All lectures.

K-means clustering

01

K-means

Partition N observations into K clusters, each observation belonging to the cluster with the nearest centroid. Put (\mathbf{x}_1,\dots,\mathbf{x}_N) into K sets S=\{S_1,\dots,S_K\} so as to minimize the within-cluster sum of squares (WCSS), that is the variance:

\arg\min_S\sum_{i=1}^K\sum_{\mathbf{x}\in S_i}\lVert\mathbf{x}-\boldsymbol\mu_i\rVert^2=\arg\min_S\sum_{i=1}^K\lvert S_i\rvert\,\mathrm{Var}[S_i]

where \boldsymbol\mu_i is the centroid of S_i. A naive implementation:

  1. Initialize the centroids \boldsymbol\mu_1,\dots,\boldsymbol\mu_K\in\mathbb{R}^D at random.
  2. Repeat until convergence:
    • for every i, assign the class c_i=\arg\min_j\lVert\mathbf{x}_i-\boldsymbol\mu_j\rVert^2
    • for every j, update the centroid \boldsymbol\mu_j=\dfrac{\sum_{i=1}^N\mathbb{1}\{c_i=j\}\,\mathbf{x}_i}{\sum_{i=1}^N\mathbb{1}\{c_i=j\}}

K-means, step by step

Three panels: random initial centroids, the assignment after one iteration, and the converged clusters with their centroids.

Assign every point to its nearest centroid, move every centroid to the mean of its points, repeat. Each step can only lower the WCSS, so the algorithm converges, though possibly to a local minimum: hence several random restarts.

How many clusters?

How do you choose K? A common rule is the elbow method: compute the WCSS for several values of K and pick the K where the curve bends, the point after which more clusters bring diminishing returns.

Consider the transmission over the non-linear channel of the SVM class activity in lecture 3. Use K-means to cluster the received samples, and show the elbow plot.

Activity 4: the outcome

# the received samples of the non-linear channel
X, y = data_rx, 0.5*data_tx + 0.5

kmeans = KMeans(init="random", n_clusters=2, n_init=10,
                max_iter=300, random_state=42)
label = kmeans.fit_predict(X)
print(kmeans.cluster_centers_)

# the elbow: the SSE for K = 1, ..., 10
sse = []
for k in range(1, 11):
    kmeans = KMeans(n_clusters=k, init="random", n_init=10,
                    max_iter=300, random_state=42)
    kmeans.fit(X)
    sse.append(kmeans.inertia_)
[[2.99541924]
 [0.34883493]]

SSE against the number of clusters: a sharp drop up to three, then flat.

the elbow is at K=3

With K=2, one centroid lands on the samples pushed to +3, the other halfway between -1 and +1. The elbow says three clusters: -1, +1 and +3, although only two symbols were sent. Clustering finds the structure of the received signal, not the labels.

Principal component analysis

02

Principal component analysis

Principal component analysis (PCA) reduces dimensionality: it maps the data linearly from \mathbb{R}^D to a lower-dimensional \mathbb{R}^K, K<D.

Read it as a compression scheme that removes redundant information. It is an orthogonal linear transformation of the training data

\mathbf{X}=\begin{bmatrix}x_{11}&\cdots&x_{1D}\\\vdots&\ddots&\vdots\\x_{N1}&\cdots&x_{ND}\end{bmatrix}

into a new coordinate system where the greatest variance lies along the first coordinate, the second greatest along the second, and so on.

A cloud of points stretched along a diagonal: the direction \mathbf{w}_1 carries almost all the spread, the orthogonal \mathbf{w}_2 very little. Which component would you remove?

An elongated cloud of points with two orthogonal arrows: a long one along the cloud and a short one across it.

The transformation

The transformation is defined component by component, for every observation \mathbf{x}_i (the i-th row of \mathbf{X}), as

t_{ij}=\mathbf{x}_i\cdot\mathbf{w}_j,\qquad\mathbf{w}_j=\begin{bmatrix}w_{1j}\\\vdots\\w_{Dj}\end{bmatrix},\qquad i=1,\dots,N,\quad j=1,\dots,K

Compactly:

\mathbf{T}=\begin{bmatrix}t_{11}&\cdots&t_{1K}\\\vdots&\ddots&\vdots\\t_{N1}&\cdots&t_{NK}\end{bmatrix}=\begin{bmatrix}x_{11}&\cdots&x_{1D}\\\vdots&\ddots&\vdots\\x_{N1}&\cdots&x_{ND}\end{bmatrix}\begin{bmatrix}w_{11}&\cdots&w_{1K}\\\vdots&\ddots&\vdots\\w_{D1}&\cdots&w_{DK}\end{bmatrix}=\mathbf{X}\mathbf{W}

Maximizing the variance

The first component maximizes the variance:

\mathbf{w}_1=\arg\max_{\lVert\mathbf{w}\rVert=1}\sum_{i=1}^N(\mathbf{x}_i\cdot\mathbf{w})^2=\arg\max_{\lVert\mathbf{w}\rVert=1}\lVert\mathbf{X}\mathbf{w}\rVert^2=\arg\max_{\mathbf{w}}\frac{\mathbf{w}^T\mathbf{X}^T\mathbf{X}\mathbf{w}}{\mathbf{w}^T\mathbf{w}}

This Rayleigh quotient is maximized by the eigenvector of \boldsymbol\Sigma=\mathbf{X}^T\mathbf{X} with the largest eigenvalue. More generally, the columns of \mathbf{W} are the eigenvectors of \boldsymbol\Sigma, and the j-th eigenvalue

\lambda_j=\sum_{i=1}^Nt_{ij}^2=\sum_{i=1}^N(\mathbf{x}_i\cdot\mathbf{w}_j)^2

is the variance along the axis \mathbf{w}_j. If \lambda_j is small, that component can go without losing much information. How many to keep? The smallest K that retains a fraction r of the total variance:

K=\min\Big\{k:\ \frac{\sum_{i=1}^k\lambda_i}{\sum_{i=1}^D\lambda_i}\ge r\Big\}

PCA, step by step

  1. Standardize the dataset \mathbf{X}.
  2. Build its covariance matrix \boldsymbol\Sigma.
  3. Decompose \boldsymbol\Sigma into eigenvectors and eigenvalues.
  4. Select the K eigenvectors with the K largest eigenvalues.
  5. Stack them into the projection matrix \mathbf{W}.
  6. Transform the D-dimensional dataset into the K-dimensional one: \mathbf{T}=\mathbf{X}\mathbf{W}.

Load the MNIST digits dataset and plot the top 2 principal components in 2D. Can you reconstruct the digits from only 2 or 3 components?

Activity 5: the outcome

(train_X, train_y), (test_X, test_y) = mnist.load_data()
X_train = np.reshape(train_X, (60000, 784))
K = 2    # dimension of the compressed space

X_train_std = StandardScaler().fit_transform(X_train)
Sigma = np.matmul(X_train_std.T, X_train_std)  # 784 x 784

# the eigenvectors of the K largest eigenvalues
eig_values, eig_vectors = eigh(Sigma, eigvals=(784-K, 783))
X_projected = np.matmul(X_train_std, eig_vectors)
PCA basis dimension: (784, 2)
Projected data: (60000, 2)

The first nine MNIST training digits: 5, 0, 4, 1, 9, 2, 1, 3, 1.

The 60,000 MNIST digits projected on two principal components, coloured by digit: the zeros form their own region at the top, the other classes overlap.

60,000 digits, from 784 dimensions to 2

Two components out of 784 already set the zeros apart from the rest, but the other classes pile on top of each other: two numbers are too few to tell ten digits apart, let alone to redraw them.