Due: Friday, Mar. 5, 2027.
It is often useful to view an image as a random process. An eigen decomposition of the covariance matrix reveals the principal directions of variation between images in a collection. This has applications in image coding, image classification, and object recognition. This lab explores image covariance, covariance estimation, and eigen decomposition of images. These ideas are then used to design a basic image classifier.
You direct Claude, or another agentic AI, to write the code from the definitions and signatures on this page. You run the experiments and explain the results. You are graded on your specification, the checks you run, and your reading of the results.
lab7-data.zip
(390 KB) holds 338 PNG images of typed lower-case letters, each 64 by
64 pixels with 8 bits per pixel. It unzips to a folder
data:
arial, bookman_old_style,
century, comic_sans_ms,
courier_new, fixed_sys,
georgia, microsoft_sans_serif,
palatino_linotype, shruti,
tahoma, times_new_roman). Each folder
holds a.png to z.png, so there are 312
training images.veranda, with the
26 letters in a font that is not in the training set.From the shell, in the folder that holds lab7.py:
wget https://charlesbouman.org/ece63700/labs/lab7-data.zip unzip lab7-data.zip
lab7.py, which holds
functions and nothing else. Run experiments from a separate script
that imports it. Use the labs conda environment from
Lab 2.float64
tensors and torch.linalg. NumPy and matplotlib are
allowed for plotting.for loop over pixels or images. A loop over
the 26 letter classes is allowed.| Item | Experiment | Input | Function and settings |
|---|---|---|---|
| D1 | Generate Gaussian vectors (Step 2) | \(R_X\) of equation (5) | generate_gaussian, \(p = 2\), \(n = 1000\),
seed = 0 |
| D2 | Estimate, decorrelate, whiten (Step 3) | the \(X\) of D1 | sample_mean_cov, decorrelate,
whiten |
| D3 | SVD and eigenvectors (Step 4) | none | a derivation |
| D4 | Mean image and eigenimages (Step 5) | data/training, \(n = 312\), \(p = 4096\) |
pca_svd; the first 12 eigenimages in 4 rows of 3 |
| D5 | Checks of the eigenvectors (Step 6) | data/training |
pca_cov; rank threshold \(10^{-10}\sigma_1\);
eigenvectors 1 to 30 |
| D6 | Projection coefficients (Step 7) | the first four training images: a, b, c, d of
arial |
project; coefficients 1 to 10 |
| D7 | Resynthesis (Step 8) | the first training image, a of arial |
resynthesize with \(m = 1, 5, 10, 15, 20, 30\);
error curve for \(m = 0\) to \(r - 1\), with \(r\) from D5 |
| D8 | Classifier with \(B_k = R_k\) (Step 10) | data/training and data/test |
\(m = 10\) eigenvectors; class_statistics,
scaling_matrices(covs, "full"),
classify |
| D9 | Constrained classifiers (Step 11) | data/training and data/test |
\(m = 10\); "diag", "wc",
"wc_diag", "identity" |
lab7.py
Copy these helpers into lab7.py. The loop in
load_letters runs over files, so it is allowed.
import os
import numpy as np
import torch
from PIL import Image
LETTERS = "abcdefghijklmnopqrstuvwxyz"
def load_letters(folder):
"""Read folder/font/letter.png into a data matrix; column 26 * f + k is letter k of font f (fonts sorted).
returns X, (4096, n) float64 gray levels 0 to 255; labels, (n,) int64 0 (a) to 25 (z); fonts, list of names
"""
fonts = sorted(d for d in os.listdir(folder)
if os.path.isdir(os.path.join(folder, d)))
columns, labels = [], []
for font in fonts:
for k, letter in enumerate(LETTERS):
img = np.asarray(Image.open(os.path.join(folder, font, letter + ".png")),
dtype=np.float64)
columns.append(img.reshape(-1))
labels.append(k)
X = torch.from_numpy(np.stack(columns, axis=1))
return X, torch.tensor(labels, dtype=torch.int64), fonts
def to_image(x):
"""Reshape a (4096,) or (4096, 1) tensor into a (64, 64) NumPy array for display."""
return x.reshape(64, 64).detach().cpu().numpy()
A Gaussian random vector \(X = [X_1, \dots, X_p]^t\) with mean \(\mu\) and covariance \(R\) has the density
$$ p(x) = \frac{1}{(2\pi)^{p/2} |R|^{1/2}} \exp\left\{ -\frac{1}{2} (x - \mu)^t R^{-1} (x - \mu) \right\} \ , \tag{1} $$where \(\mu = E[X]\), and the covariance \(R = E[(X - \mu)(X - \mu)^t]\) is positive definite and symmetric. In this step \(\mu = 0\). The eigen decomposition of \(R\) is
$$ R = E \Lambda E^t \ , \tag{2} $$where the columns of \(E = [e_1, \dots, e_p]\) are the \(p\) eigenvectors of \(R\), and \(\Lambda = \mathrm{diag}(\lambda_1, \dots, \lambda_p)\) contains the corresponding eigenvalues. Since \(R\) is symmetric, the eigenvectors are orthogonal and can be scaled to unit length, so \(E^t E = I\).
The eigen decomposition of \(R\) can be used to decorrelate and whiten \(X\). The components of \(\tilde X = E^t X\) are uncorrelated with diagonal covariance \(\Lambda\), and therefore independent in the Gaussian case. The contours of \(p(x)\) are ellipsoidal. Their principal directions are given by the eigenvectors in \(E\), and the lengths of the principal axes are proportional to \(\sqrt{\lambda_k}\). Normalizing the variance of each element of \(\tilde X\) produces a whitened random vector with i.i.d. \(N(0, 1)\) components,
$$ W = \Lambda^{-1/2} E^t X \ . \tag{3} $$By inverting equation (3), the random vector \(X\) with covariance \(R\) can be generated by applying the transformation \(E \Lambda^{1/2}\) to the i.i.d. \(N(0, 1)\) random variables in \(W\):
$$ X = E \Lambda^{1/2} W \ . \tag{4} $$In this step you use the covariance
$$ R_X = \begin{bmatrix} 2 & -1.2 \\ -1.2 & 1 \end{bmatrix} \ . \tag{5} $$def eig_sorted(R):
"""Return lam (p,), eigenvalues of symmetric (p, p) R largest first, and E (p, p), column k the unit eigenvector of lam[k]."""
def generate_gaussian(R, n, seed):
"""Draw W (p, n) i.i.d. N(0, 1) with a torch.Generator seeded by seed; return W, X_tilde = Lambda^(1/2) W, X = E X_tilde."""
torch.linalg.eigh returns eigenvalues in increasing order,
so eig_sorted reverses them and the eigenvector columns.
Draw \(W\) with torch.randn.
Task 2a. Report the eigenvalues and eigenvectors of \(R_X\).
Generate the vectors of D1 and make scatter plots of \(W\),
\(\tilde X\), and \(X\) in three figures with the same axis limits,
equal axis scales (ax.set_aspect("equal")), and labeled
axes.
Task 2b. Check. Report the largest entry of \(|E \Lambda E^t - R_X|\), which must be below \(10^{-12}\). Report the largest entry of \(|\hat R_W - I|\), where \(\hat R_W\) is the sample covariance of \(W\). This is a statistical error, of order \(1/\sqrt{n} \approx 0.03\).
The eigenvalues and eigenvectors of \(R_X\), the three scatter plots, a sentence on what each transformation does to the points, and the two checks.
We often do not know the true covariance, but we can obtain an estimate from a set of training data. Suppose we have \(n\) i.i.d. training vectors, arranged as columns in a \(p \times n\) data matrix \(X = [X_1, \dots, X_n]\). If the mean is unknown, the unbiased estimates are
$$ \hat\mu = \frac{1}{n} \sum_{i=1}^{n} X_i \ , \qquad \hat R = \frac{1}{n-1} \sum_{i=1}^{n} (X_i - \hat\mu)(X_i - \hat\mu)^t = \frac{1}{n-1} Z Z^t \ , \tag{6} $$where \(Z = [X_1 - \hat\mu, \dots, X_n - \hat\mu]\) holds the mean-centered data vectors. With \(\hat R = E \Lambda E^t\), the decorrelated and whitened vectors are
$$ \tilde X_i = E^t (X_i - \hat\mu) \ , \qquad W_i = \Lambda^{-1/2} E^t (X_i - \hat\mu) \ . \tag{7} $$def sample_mean_cov(X):
"""Return mu (p, 1) and the unbiased covariance R_hat (p, p), with 1/(n-1), of the columns of X (p, n)."""
def decorrelate(X):
"""Return X_tilde = E^t (X - mu), (p, n), where mu and R_hat = E Lambda E^t come from sample_mean_cov(X)."""
def whiten(X):
"""Return W = Lambda^(-1/2) E^t (X - mu), (p, n), where mu and R_hat = E Lambda E^t come from sample_mean_cov(X)."""
Task 3a. Estimate \(\hat\mu\) and \(\hat R_X\) from the \(X\) of D1. List them next to \(R_X\), and report the largest entry of \(|\hat R_X - R_X|\).
Task 3b. Decorrelate and whiten the vectors. Make scatter plots of \(\tilde X_i\) and \(W_i\) as in Task 2a, and list \(\hat R_W\).
Task 3c. Check. Report the off-diagonal entry of the sample covariance of the \(\tilde X_i\), the largest entry of \(|\hat R_W - I|\), and the largest entry of the sample mean of the \(W_i\). All three must be below \(10^{-12}\). A value near 0.001 means the code mixes \(1/n\) and \(1/(n-1)\).
\(R_X\), \(\hat\mu\), and \(\hat R_X\) with the largest difference, the scatter plots of \(\tilde X_i\) and \(W_i\), \(\hat R_W\), and the three checks.
The eigen decomposition of the sample covariance is often not practical for images, where the dimension \(p\) is the number of pixels and is much larger than the number of training images \(n\). The covariance of a 400 by 400 image would contain about 25 billion elements. However, the columns of \(\hat R\) are all linear combinations of the same \(n\) vectors, so \(\hat R\) has at most \(n\) nonzero eigenvalues. We can compute them, and their eigenvectors, without computing \(\hat R\), using the singular value decomposition (SVD). The SVD of a \(p \times n\) matrix \(Z\) with \(p > n\) is
$$ Z = U \Sigma V^t \ , \tag{8} $$where both \(U \in \mathbb{R}^{p \times n}\) and \(V \in \mathbb{R}^{n \times n}\) have orthonormal columns, and \(\Sigma = \mathrm{diag}(\sigma_1, \dots, \sigma_n)\) holds the singular values in descending order. The procedure is:
torch.linalg.svd(Z, full_matrices=False).Task 4. Substitute equation (8) into \(\hat R = Z Z^t\) and show that \(\hat R u_k = \sigma_k^2 u_k\). Say why the other \(p - n\) eigenvalues are 0.
Your derivation, in a few lines.
The eigenvectors of an image covariance matrix are also called eigenimages. The eigenimages corresponding to the largest eigenvalues represent the directions in \(\mathbb{R}^p\) of the greatest variation among a set of images.
def pca_svd(X):
"""From X (p, n), p > n, form Z = (X - mu) / sqrt(n - 1) and its reduced SVD; return mu (p, 1), lam = sigma_k^2 (n,) largest first, U (p, n)."""
Task 5a. Load load_letters("data/training"), call
pca_svd, and display the mean image \(\hat\mu\) on the
gray scale 0 to 255.
Task 5b. Display \(u_1, \dots, u_{12}\) in one figure with 4
rows of 3, using to_image. Use one gray scale from \(-a\)
to \(a\), where \(a\) is the largest absolute value among them, one
colorbar, and the index as each title.
The mean image and the first 12 eigenimages, with colorbars.
For \(p = 4096\) you can still form \(\hat R\) and decompose it
directly. This checks pca_svd.
def pca_cov(X):
"""Check of pca_svd: form R_hat with sample_mean_cov and call eig_sorted; return mu (p, 1), lam (p,) largest first, E (p, p)."""
Task 6a. Rank. Count the singular values above \(10^{-10} \sigma_1\). This count \(r\) is the rank of \(Z\).
Task 6b. Eigenvalues. Report the largest
\(|\sigma_k^2 - \lambda_k| / \sigma_k^2\) for \(k = 1, \dots, r\),
between pca_svd and pca_cov. Plot both sets
against \(k\) on one graph with a logarithmic vertical axis.
Task 6c. Eigenvectors. For \(k = 1, \dots, 30\), take the smaller of the largest entries of \(|u_k - e_k|\) and \(|u_k + e_k|\). Report the largest of these 30 values, and the largest entry of \(|U^t U - I|\).
Task 6d. Time pca_svd and pca_cov
with time.perf_counter.
The eigenvalues and eigenvectors must agree below \(10^{-10}\). If \(u_k\) matches some \(e_j\) with \(j \ne k\), the two are sorted differently.
The rank \(r\), the eigenvalue plot, the largest eigenvalue and eigenvector differences, the orthonormality check, and the two times.
Let \(U_m = [u_1, \dots, u_m]\). The projection coefficients of an image \(x\) are
$$ y = U_m^t (x - \hat\mu) \ . \tag{9} $$These coordinates along the eigenvector directions form a feature vector characterizing the image. Note that \(y\) is not an image.
def project(X, mu, U, m):
"""Return Y = U_m^t (X - mu), (m, n), where U_m is the first m columns of U (p, r), r >= m."""
Task 7. Compute the coefficients of all training images. Plot
coefficients 1 to 10 of a, b, c, d of arial against
\(k\) on one graph, one line per letter, with a legend.
The plot of the projection coefficients.
We can approximate the original image from a linear combination of the eigenimages,
$$ \hat x = \hat\mu + \sum_{k=1}^{m} u_k y_k = \hat\mu + U_m y \ . \tag{10} $$The mean square error of this approximation is the sum of the remaining eigenvalues,
$$ E\left[ \| \hat X - X \|^2 \right] = \sum_{k=m+1}^{p} \lambda_k \ . \tag{11} $$So the approximation is closest in the MSE sense if we use the largest eigenvalue components. This approximation is called principal component analysis (PCA).
def resynthesize(Y, mu, U):
"""Return X_hat = U_m Y + mu, (p, n), with m = Y.shape[0] and U (p, r), r >= m."""
Task 8a. Resynthesize a of arial with
\(m = 1, 5, 10, 15, 20, 30\). Show the original and the six results in
one figure on the gray scale 0 to 255 with one colorbar.
Task 8b. Check. For \(m = 0, 1, \dots, r - 1\), compute \(\|\hat x - x\|^2\) for the first image and its average over all \(n\) training images. Plot both against \(m\) with a logarithmic vertical axis, together with the prediction \(\frac{n-1}{n} \sum_{k=m+1}^{r} \lambda_k\) for the average. Count the values of \(m\) where the first image's error increases; the count must be 0. Report the largest relative difference between the average and the prediction; it must be at round-off level. The factor \((n-1)/n\) appears because \(\hat R\) divides by \(n-1\).
The original and six resynthesized images, the error plot, the count of increases, and the largest relative difference.
In a classification problem we are given an input image \(x\) that has to be assigned to one of several classes \(C_k\), here the \(K = 26\) letters. If all classes are equally likely, the class with the greatest posterior probability is the maximum likelihood (ML) class estimate \(k^* = \arg\max_k p(x \mid C_k)\). If the images in each class are Gaussian, \(N(\mu_k, R_k)\), then
$$ k^* = \arg\min_k \left\{ (x - \mu_k)^t R_k^{-1} (x - \mu_k) + \log |R_k| \right\} \ . \tag{12} $$The first term is a weighted distance of the image to the class mean. Two issues arise with high-dimensional data. First, the estimate of \(R_k\) is often not invertible because of the limited training data. Second, each \(R_k\) is enormous. Both are addressed by transforming each image to the lower dimensional vector \(y = A^t (x - \hat\mu)\) of equation (9). Here \(A = U_{10}\) holds the first 10 eigenvectors of the whole training set, irrespective of class, and \(\hat\mu\) is its mean image. Then apply equation (12) to \(y\) with the class estimates
$$ \hat\mu_k = \frac{1}{N_k} \sum_{i=1}^{N_k} y_i^{(k)} \ , \qquad \hat R_k = \frac{1}{N_k - 1} \sum_{i=1}^{N_k} (y_i^{(k)} - \hat\mu_k)(y_i^{(k)} - \hat\mu_k)^t \ , \tag{13} $$where \(y_i^{(k)}\) is the \(i\)-th training vector of class \(k\) and \(N_k = 12\).
def class_statistics(Y, labels, K):
"""From Y (m, n) and labels (n,) in 0 to K-1, return means (K, m) and unbiased covs (K, m, m), with 1/(N_k - 1)."""
Task 9a. Compute the feature vectors \(Y\) of the training images and \(Y_{\text{test}}\) of the test images, both with the same \(\hat\mu\) and \(A\) from the training set. Compute the class means and covariances.
Task 9b. Check. The training features must have sample mean 0 and sample covariance \(\mathrm{diag}(\lambda_1, \dots, \lambda_{10})\). Report the largest entry of \(|\hat\mu_Y|\) relative to \(\sqrt{\lambda_1}\), and the largest entry of \(|\hat R_Y - \mathrm{diag}(\lambda_1, \dots, \lambda_{10})|\) relative to \(\lambda_1\). Both must be below \(10^{-12}\).
The classifier uses a matrix \(B_k\) in place of \(R_k\):
$$ k^* = \arg\min_k \left\{ (y - \hat\mu_k)^t B_k^{-1} (y - \hat\mu_k) + \log |B_k| \right\} \ . \tag{14} $$In this step \(B_k = \hat R_k\).
def scaling_matrices(covs, kind):
"""Return B (K, m, m) from covs (K, m, m): "full" R_k, "diag" diag(R_k), "wc" R_wc = mean of R_k, "wc_diag" diag(R_wc), "identity" I."""
def classify(Y, means, B):
"""Return (n,) int64, for each column of Y the class k minimizing (y - mu_k)^t B_k^(-1) (y - mu_k) + log |B_k|."""
Use torch.linalg.solve for \(B_k^{-1}(y - \hat\mu_k)\)
and torch.linalg.slogdet for \(\log |B_k|\).
Task 10. Classify the 26 test images with
kind="full". Make a table of the misclassified test
letters: the true letter and the chosen letter. Report the number of
errors and the error rate.
The table of misclassified test letters, the number of errors, and the error rate.
A probable reason for the errors of D8 is the limited number of training images available for estimating each \(\hat R_k\). A more constrained matrix \(B_k\) might reduce the errors. Try these four:
"diag": \(B_k = \Lambda_k\), the diagonal of
\(\hat R_k\). Each class has a different diagonal covariance."wc": \(B_k = R_{wc}\), the average within-class
covariance \(R_{wc} = \frac{1}{K} \sum_{k=1}^{K} \hat R_k\). Each
class has the same covariance."wc_diag": \(B_k = \Lambda\), the diagonal of
\(R_{wc}\). Each class has the same diagonal covariance."identity": \(B_k = I\). Each class has identity
covariance around a different mean.Each case still computes the difference between the input and each class mean, but with a different scaling matrix \(B_k\).
Task 11a. Classify the 26 test images with each of the four. For each, make the table of D8 and report the number of errors and the error rate.
Task 11b. Check. With \(B_k = I\), equation (14) picks the
nearest class mean. Compute it directly with
torch.cdist and count the test images where it differs
from classify. The count must be 0.
Task 11c. Classify the 312 training images with all five classifiers and report the training errors of each.
The four tables, a summary table of test and training errors for all five classifiers, the check, and which classifier worked best.
You directed your AI assistant to write twelve functions:
eig_sorted, generate_gaussian,
sample_mean_cov, decorrelate,
whiten, pca_svd, pca_cov,
project, resynthesize,
class_statistics, scaling_matrices, and
classify.
The specification you gave your AI assistant, quoted. Show any correction you made during the build and say what was wrong.
Answer each in a few sentences, citing your own figures and numbers.
Your answers to the five questions.
Submit two files through Brightspace:
lab7.py, as a plain .py file.
Do not paste the code into the report, and do not send a zip file.
Commit lab7.py to your
image-processing-labs repository under lab7
and push it before you submit.
Concise and clear beats long.