Skip to main content

Homework 08: Principal Component Analysis and Singular Value Decomposition

_Due: Tuesday, November 17 at 11:59 PM _

Overview

An 8 × 8 image contains 64 pixel values, but those values are not independent: neighboring pixels and recurring shapes give the data structure. Principal component analysis (PCA) uses that structure to describe observations with fewer coordinates. The central question in this assignment is what those coordinates preserve, and what we lose when we discard the rest.

You will connect the eigenvalues and eigenvectors from class to a PCA implementation using singular value decomposition (SVD). Then you will use your implementation to explore handwritten digits: how many components capture most of their variation, what a two-dimensional view reveals, and how recognizable the images remain after reconstruction. A final, shorter experiment uses SVD on a single image to make the tradeoff between quality and storage visible.

Getting started

The HW08 starter bundle on Piazza contains the written problems, data, public tests, and code for running the experiments. Plot layouts, input validation, and data loading are already provided so that your work can focus on the PCA calculations and their interpretation.

There are seven functions to complete: fit(), transform(), and reconstruct_data() in PCA.py; numerical_checks(), components_for_variance(), and compare_with_sklearn() in run_pca.py; and low_rank_approximation() in run_svd.py. Their docstrings describe their inputs and outputs. The remaining code connects these functions to the experiments below.

Use Python 3.10 or newer. From the extracted homework directory, install the packages and try the public tests:

python3 -m pip install -r requirements.txt
python3 -m unittest -v test_hw08

NumPy supplies the SVD algorithm through np.linalg.svd(). Your responsibility is to use its output to implement centering, projection, reconstruction, variance calculations, and component selection. Scikit-learn’s PCA is reserved for the comparison in Part 2. Keep type annotations and docstrings in your functions, and keep experiment code under the provided main() guards. The plotting helpers save labeled figures in figures/.

Part 0: Problem set

The written problems give you a small-scale view of the eigenvectors, eigenvalues, and PCA calculations that your code will carry out on larger matrices. Complete HW08_written_problems_student.pdf from the starter bundle, showing your work. You may write your answers by hand or typeset them. Submit the completed PDF with the same filename.

Part 1: Implement PCA using SVD (30 points)

From observations to principal coordinates

Throughout the PCA implementation, each row of \(X\) is an observation and each column is a feature. Thus \(X\) has shape \((n,p)\) for \(n\) observations with \(p\) features. PCA describes variation around the feature means, so the first step is to subtract the column means:

\[X_c=X-\mu.\]

This is also why the fitting mean must be saved: later observations need to be expressed relative to the same origin. Centering each new batch around its own mean would change the coordinate system.

The reduced SVD provides the directions and the amount of variation along them:

U, s, Vt = np.linalg.svd(X_centered, full_matrices=False)

With \(r=\min(n,p)\), the returned shapes are \(U:(n,r)\), \(s:(r,)\), and \(V^T:(r,p)\). NumPy orders the singular values from largest to smallest; the corresponding rows of Vt are the principal directions. See the NumPy SVD documentation for the return-value conventions.

Keeping the first \(k\) directions gives a matrix \(W_k=V^T[:k]\) of shape \((k,p)\). An observation then has \(k\) principal coordinates instead of \(p\) original features. Projection and reconstruction are:

\[Z=(X-\mu)W_k^T,\qquad \widehat X=ZW_k+\mu.\]

Reconstruction returns to the original feature space, but discarded components are no longer available. The result is generally an approximation of the original observation.

The connection to covariance appears in the sample variances:

\[\lambda_j=\frac{s_j^2}{n-1},\qquad q_j=\frac{s_j^2}{\sum_{\ell=1}^{r}s_\ell^2}.\]

Here \(\lambda_j\) is the covariance eigenvalue associated with direction \(j\), and \(q_j\) is its fraction of the total variance. The denominator uses all singular values, even when the model keeps only \(k\) components: we want the fraction of the original variation that survives the reduction.

The PCA class

The three methods separate learning a coordinate system from using it:

class PCA:
    def __init__(self, n_components: int) -> None:
        ...

    def fit(self, X: np.ndarray) -> "PCA":
        ...

    def transform(self, X: np.ndarray) -> np.ndarray:
        ...

    def reconstruct_data(self, Z: np.ndarray) -> np.ndarray:
        ...

fit() learns from \(X\), stores the following attributes, and returns self. A later call to fit() replaces that fitted state.

Attribute Shape Meaning
mean_ (p,) Feature means of the fitting data
components_ (k, p) Retained principal directions, one per row
singular_values_ (k,) Singular values for the retained directions
explained_variance_ (k,) Sample variances along those directions
explained_variance_ratio_ (k,) Fractions of total variance explained

transform() maps an array of shape (m, p) to coordinates of shape (m, k) using the stored fitting mean and directions. reconstruct_data() maps coordinates of shape (m, k) back to observations of shape (m, p), adding the fitting mean. None of these methods should modify its input array.

Our reconstruction method uses the terminology from class. Scikit-learn calls the corresponding method inverse_transform(), which you will use for its model in Part 2.

Inputs are real numeric NumPy arrays, and n_components is a Python int; support for lists, strings, complex arrays, or arbitrary object conversion is outside the assignment. The supplied validation requires finite 2D fitting data with at least two rows, one column, nonzero total centered variance, and 1 <= n_components <= min(n, p). It raises ValueError for invalid dimensions, nonfinite values, invalid component counts, or incompatible transformation shapes, and RuntimeError for a transformation before fitting. Keep these provided checks in place while completing the calculations.

Checking the geometry

A useful implementation check tests a mathematical property rather than just one expected output. Complete numerical_checks() in run_pca.py with executable checks of these three properties:

Use approximate comparisons such as np.allclose; exact floating-point equality is not appropriate here. Include these checks in your submitted code.

Part 2: Handwritten digits (30 points)

Each handwritten digit is an 8 × 8 image. Flattening it into a row gives 64 features, each an intensity between 0 and 16. Across the 1,797 images, PCA can find patterns of pixel variation that individual images have in common. These experiments use your PCA implementation from Part 1 to explore that structure.

The starter includes a local copy of scikit-learn’s digits dataset in data/digits.npz, in its original order. The provided driver loads it through load_digits_data(). The dataset documentation provides its description and attribution.

Choosing a smaller representation (8 points)

Use all observations for this descriptive analysis; no classifier or train/test evaluation is required. Center the pixels without standardizing them, since they measure the same quantity on the same scale. Digit labels may color the plots but must not influence fitting PCA or selecting k.

The cumulative explained-variance curve shows how much variation is preserved as components are added. The driver fits all 64 components and saves this curve in figures/variance.pdf, with component count starting at 1. Complete components_for_variance() in run_pca.py so it reports the smallest counts reaching at least 90% and 95% cumulative variance. Compute those counts from the ratios rather than hard-coding them.

In README.md, report the component counts for 90% and 95% cumulative variance. Also explain why multiplying one feature by 1,000 could affect PCA, when standardization might help, and how a zero-variance feature should be handled when standardizing.

Looking at two dimensions (8 points)

A two-dimensional projection makes the dataset easy to inspect, while keeping only its first two principal coordinates. The driver saves this view in figures/digits_2d.pdf, coloring points by digit. The axes identify PC1 and PC2 and their explained-variance percentages; a discrete colorbar identifies digits 0–9. Small, transparent markers help show overlapping observations. As you inspect the plot, consider both the visible groups and the information that may have been lost in the projection.

In README.md, identify which digits overlap in the two-dimensional plot. Explain why this overlap does not establish that the original 64-dimensional data are inseparable. Run python3 run_pca.py to generate the figure using your PCA implementation. No additional code is required for this subsection.

Reconstructing the images (8 points)

Reconstruction lets you see what a reduced representation preserves in the original pixel space. The driver takes the first occurrence of each digit 0–9 and places its original image beside reconstructions with k = 2, 10, 30, 64. Each row corresponds to a digit; the five columns show the original and the four reconstructions, reshaped to 8 × 8 images. A common grayscale range of 0–16 makes the visual comparisons meaningful. The figure is saved as figures/digits_reconstructed.pdf.

Alongside the images, the driver prints mean squared reconstruction error for each k, measured over all observations and all pixels. These errors describe the whole dataset, whereas the figure shows only ten examples. Use both when discussing the effect of keeping more components.

Run python3 run_pca.py to generate the reconstructions and printed errors using your PCA implementation. No additional code is required for this subsection.

In README.md, report the reconstruction error for each k and describe how visual quality changes as more components are retained. Does retaining 95% variance guarantee 95% classification accuracy? Explain.

Comparing implementations (6 points)

Scikit-learn gives you an independent check of your implementation. Complete compare_with_sklearn() in run_pca.py by fitting sklearn.decomposition.PCA(n_components=10, svd_solver="full") on the same data as your 10-component model. Report the largest absolute differences in explained-variance ratios and reconstructed data. Individual component signs may differ; the comparison should not require those signs to match. Explain any differences beyond small numerical tolerances. Include the reported maximum differences and your explanation in README.md.

Finally, consider using either implementation before a classifier. In README.md, explain which data you would use to fit the PCA mean and directions, and how you would transform held-out observations.

Part 3: Low-rank image approximation (20 points)

In the digits experiment, one row of the data matrix represents a whole image and one column represents a pixel feature. SVD can also be applied directly to a single image matrix, whose rows and columns are spatial positions. This short experiment uses the same decomposition in a different setting, so pay attention to what the matrix represents.

The driver in run_svd.py loads the provided 128 × 128 grayscale image with load_svd_image() and computes its reduced SVD without centering. It reuses that decomposition at several ranks. Complete low_rank_approximation(U, s, Vt, k) to combine the first \(k\) terms:

\[A_k=U_{:,:k}\Sigma_kV^T_{:k,:},\qquad \Sigma_k=\operatorname{diag}(s_{:k}).\]

Broadcasting is fine in place of constructing the diagonal matrix. Once the function is complete, the driver saves the original and approximations for k = 1, 2, 5, 10 together in figures/svd_image.pdf, using a common grayscale range of 0–1. This comparison figure is worth 10 points.

The remaining 10 points are for one short paragraph in README.md. Compare the meanings of rows and columns in the digits PCA matrix and this single-image matrix, and explain why uncentered image approximation is a different task from fitting PCA across images. Then describe the visible changes with k and choose a displayed rank that balances quality and storage. Support your choice with the counts: an \(m\times p\) image stores \(mp\) numbers, while its rank-\(k\) factors store \(mk+k+kp\). Assume equal storage per number. These counts describe storing the factors, rather than a full reconstructed image or a PNG file.

Running and submission

Your completed homework should run from its directory without interactive input:

python3 run_pca.py
python3 run_svd.py

Before submitting, rerun both programs, check the numerical results, and inspect all four figures. The printed results should be clearly labeled. Alongside your analysis, README.md should include the run commands, Python and package versions, an estimate of time spent, and any incomplete portions. Grading considers mathematical reasoning, correct implementation, reproducible experiments, and clear interpretation.

Submit a ZIP to HW08 on Gradescope with the following files at its root:

HW08_written_problems_student.pdf
PCA.py
run_pca.py
run_svd.py
README.md
data_utils.py
validation.py
plotting.py
requirements.txt
test_hw08.py
figures/
  variance.pdf
  digits_2d.pdf
  digits_reconstructed.pdf
  svd_image.pdf

Include any additional helper modules needed to run your code. Leave out virtual environments, installed packages, and the provided data/ directory; the grader supplies the same data files alongside your code.

Academic integrity

Follow the course collaboration and attribution policies. Credit permitted sources or assistance. Your code and interpretation must reflect your own understanding.