SYDE 572 · Introduction to Pattern Recognition

Assignment 3

PCA, data visualization and Isomap

Larissa Rudenko

Setup

The data is the Iris dataset from the UCI link in the assignment. I used the iris.data file from UCI: 150 flowers, 4 features, and 3 classes with 50 flowers each. The feature columns, in order, are sepal length, sepal width, petal length and petal width, all in cm. The classes are Iris-setosa, Iris-versicolor and Iris-virginica.

Where the class labels are used. The labels only set the colors in the plots, and they are used to score the classification in Part 5. PCA and Isomap never see them.

PCA. I used scikit-learn's PCA, which centers the data (subtracts the mean of each feature) and does not scale it. I did not standardize the features because all four are measured in cm. The sign of a principal axis is arbitrary, so the same axis could also be reported with all its entries flipped.

Random seed. The only random choice on this page is how the data is split into folds for the cross-validation in Part 5. That uses seed 572, picked before I looked at any results.

Software. Python 3.14.3, numpy 2.5.3, matplotlib 3.11.2 and scikit-learn 1.9.1.

The by-hand work for Part 1 is in the PDF linked in the Hand calculations section. The code that checks it is part1_check.py.

Part 1 - PCA by hand

This part was done by hand, and the handwritten work is in the PDF in the Hand calculations section. The dataset is the 5 examples (-2, -1), (-1, 0), (0, 1), (1, 2) and (2, 3). These are the results:

QuestionAnswer
1. First principal component\(\frac{1}{\sqrt{2}}[1, 1]^T\)
2. Reconstruction error of (3, 3)\(\sqrt{0.5} \approx 0.7071\)
3. Reconstruction error of (3, 4)0

Comment. All 5 examples satisfy x2 = x1 + 1, so after centering they lie on a line through the origin in the direction (1, 1). The first principal component points along that line, and the second eigenvalue of the covariance matrix is 0, so projecting these 5 examples onto the first component loses nothing. The point (3, 4) satisfies the same equation, so it is reconstructed exactly and its error is 0. The point (3, 3) does not (4 ≠ 3 + 1), so it is off the line, and its error of 0.7071 is its distance to that line. part1_check.py repeats the calculation with numpy and with scikit-learn's PCA, and both agree with these answers.


Part 2 - Data Visualization

Marginalizing here means keeping only some of the features and dropping the rest, so the data is projected onto the axes that are kept. I show one feature, two features and three features. The axes are an arbitrary choice, so I picked petal length and sepal width for the one feature case, two pairs for the two feature case (one petal pair and one sepal pair, to compare them), and petal length, petal width and sepal length for three features.

histograms of petal length and sepal width for each class
Fig 1. One feature at a time: petal length (left) and sepal width (right), one color per class.
scatter plots of two feature pairs
Fig 2. Two features at a time: petal length vs petal width (left) and sepal length vs sepal width (right).
3D scatter of petal length, petal width and sepal length
Fig 3. Three features at a time: petal length, petal width and sepal length.

The table gives the range (min to max) and mean of each feature for each class, all in cm.

FeatureIris-setosaIris-versicolorIris-virginica
Sepal length4.3 to 5.8 (mean 5.006)4.9 to 7.0 (mean 5.936)4.9 to 7.9 (mean 6.588)
Sepal width2.3 to 4.4 (mean 3.418)2.0 to 3.4 (mean 2.770)2.2 to 3.8 (mean 2.974)
Petal length1.0 to 1.9 (mean 1.464)3.0 to 5.1 (mean 4.260)4.5 to 6.9 (mean 5.552)
Petal width0.1 to 0.6 (mean 0.244)1.0 to 1.8 (mean 1.326)1.4 to 2.5 (mean 2.026)

Comment. The petal features show the classes much better than the sepal features. Petal length alone separates setosa from the other two, since the largest setosa value (1.9 cm) is below the smallest versicolor value (3.0 cm), but versicolor and virginica overlap on it. Plotting petal length against petal width (Fig 2, left) gives three visible groups, with versicolor and virginica next to each other and a few points near the boundary. The 3D plot (Fig 3) looks similar: setosa is clearly apart, and versicolor and virginica are close but not cleanly split. The sepal features are weaker. Sepal width overlaps across all three classes (Fig 1, right), and in sepal length vs sepal width (Fig 2, right) setosa is only roughly separated while versicolor and virginica are mixed. So the petal marginalizations highlight the classes best, but none of them splits all three perfectly.


Part 3 - PCA

I ran PCA on all 150 flowers with 4 components, on the centered data with no scaling (see Setup). The feature means that PCA subtracts are 5.8433, 3.0540, 3.7587 and 1.1987 cm.

The PCA axes

Each row below is one principal axis (a row of components_). The coefficients are in the order sepal length, sepal width, petal length, petal width, which is the column order of iris.data. Each axis has length 1, and the script checks that the four axes are orthogonal (the matrix of their dot products is the identity). The last column is the variance of the data along that axis.

AxisSepal lengthSepal widthPetal lengthPetal widthVariance along axis
PC10.3616-0.08230.85660.35884.2248
PC20.65650.7297-0.1758-0.07470.2422
PC3-0.58100.59640.07250.54910.0785
PC40.3173-0.3241-0.47970.75110.0237
About the signs. The sign of each axis is whatever scikit-learn returned. Flipping all four coefficients of an axis gives an equally valid axis, so the sign by itself has no meaning.

The data on the top axes

histogram of the data on PC1
Fig 4. The data projected onto the first principal axis (PC1).
scatter plot of PC1 against PC2
Fig 5. The data projected onto the top 2 principal axes.
3D scatter plot of PC1, PC2 and PC3
Fig 6. The data projected onto the top 3 principal axes.

Comment on the axes. PC1 is mostly petal length (0.8566), with smaller positive weights on sepal length (0.3616) and petal width (0.3588) and almost nothing from sepal width (-0.0823). PC2 is mostly sepal length and sepal width (0.6565 and 0.7297), with small petal weights (-0.1758 and -0.0747). PC1 has far more variance than the others: 4.2248, against 0.2422 for PC2, 0.0785 for PC3 and 0.0237 for PC4.

Comment on the plots. On PC1 alone (Fig 4), setosa is separated from the other two by a gap, and versicolor and virginica overlap over a short range. Adding PC2 (Fig 5) spreads the points vertically but does not separate versicolor from virginica any better, since the split between them is still mostly along PC1. Adding PC3 (Fig 6) changes little, which is consistent with its small variance. PCA never used the class labels, so the clusters in these plots come from the features alone. The colors are only there so we can read the plots.


Part 4 - Data Compression

PCA keeps the directions with the most variance, so the variance along the kept axes tells us how much of the information survives in a low-dimensional version. The connection I use is between the Frobenius norm and the variance of the centered data matrix \(X_c\) (150 rows, 4 columns), whose singular values are \(s_i\):

\[ \lVert X_c \rVert_F^2 = \sum_i s_i^2 = (n-1) \cdot (\text{total variance}) \]

The squared Frobenius norm computed directly from the entries of \(X_c\) is 680.8244, and the sum of the squared singular values is also 680.8244. Dividing by n - 1 = 149 gives a total variance of 4.5693, which equals the sum of the four feature variances.

PCSingular valueVariance (s2/(n-1))Fraction of total varianceCumulative fraction
PC125.08994.22480.92460.9246
PC26.00790.24220.05300.9776
PC33.42050.07850.01720.9948
PC41.87850.02370.00521.0000
fraction of variance explained by each principal component and the cumulative total
Fig 7. Fraction of the total variance explained by each PC, with the cumulative total and the 50% line.

1. Variance explained by the two-dimensional representation

The two-dimensional representation (the first two PCs from Part 3) is the rank 2 approximation \(X_2\) of \(X_c\). The variance it keeps is

\[ \frac{\lVert X_2 \rVert_F^2}{\lVert X_c \rVert_F^2} = \frac{s_1^2 + s_2^2}{\sum_i s_i^2} = 0.9776 \]

So the two-dimensional representation explains 0.9776 of the total variance, about 97.8%. The fraction left out is 0.0224, which is the squared Frobenius norm of the residual \(X_c - X_2\) divided by \(\lVert X_c \rVert_F^2\).

2. Number of PCs needed to explain 50% of the variance

One PC is enough. PC1 alone explains 0.9246 of the variance (about 92.5%), which is already above 50%. The cumulative fractions for 1, 2, 3 and 4 PCs are 0.9246, 0.9776, 0.9948 and 1.

Cross-check. scikit-learn's explained_variance_ratio_ gives the same fractions. The largest difference from the singular value route is about 1.6 × 10-15.

Part 5 - Non-linear Components (Isomap)

I used scikit-learn's Isomap with 3 nearest neighbours and 2 output dimensions. The code that makes the embedding is:

iso = Isomap(n_neighbors=3, n_components=2)
Z_iso = iso.fit_transform(X)

The full script is part5_isomap.py (see the Code section).

Isomap embedding of the Iris data with 3 nearest neighbours
Fig 8. Isomap embedding (3 nearest neighbours, 2 dimensions).

What Isomap does in scikit-learn

The assignment describes Isomap as computing approximate geodesic distances on a k-nearest-neighbour graph and then fitting a standard MDS model with gradient descent. In the scikit-learn source (version 1.9.1 here), the geodesic distances come from shortest paths on the neighbour graph (shortest_path), and the embedding is then computed with KernelPCA, which is an eigendecomposition. There is no gradient descent step, so the implementation differs from the description in the assignment.

The 3-nearest-neighbour graph is not connected. On all 150 flowers the graph has 2 connected components, with 50 and 100 flowers. scikit-learn printed a warning that the graph has 2 components and that it would complete the graph, so the geodesic distances between the two pieces rely on a link that sklearn added, not on a chain of real neighbours. The graphs on the training folds in the cross-validation below were also disconnected (2 components, or 3 in one fold of seed 572). Isomap itself has no random choices: fitting it a second time gave the same embedding.

Comparison with PCA on all 150 flowers

MeasurePCA, 2 componentsIsomap, 2 components
Variance explained0.9776not defined
Isomap reconstruction_error()not defined0.4373
Correlation of pairwise distances with the original 4D distances0.99840.9768
Silhouette score using the true labels0.53440.5600

For reference, the silhouette score of the original 4D data is 0.5033. Variance explained and Isomap's reconstruction error measure different things, so I do not compare those two numbers with each other. The correlation of pairwise distances is computed the same way for both methods.

Classification with a 5-nearest-neighbour classifier

I used a 5-NN classifier (5 is scikit-learn's default, chosen before I saw any results) with stratified 5-fold cross-validation, shuffled with seed 572. In each fold, PCA or Isomap is fit on the training part only, and the test part is then transformed with that fitted embedding. The last row is the classifier on the original 4D data with no embedding.

MethodMean accuracy, seed 572
PCA 2D0.9733
Isomap 2D0.9600
Original 4D0.9600

The same comparison with 50 different split seeds (0 to 49), to see how much the split matters:

MethodMeanStdMinMax
PCA 2D0.96810.00640.95330.9800
Isomap 2D0.94590.01300.91330.9867
Original 4D0.96560.00860.94670.9800

PCA had a higher mean accuracy than Isomap for 45 of the 50 seeds, and there were no ties.

Change from my first version. I first fit both embeddings on all 150 flowers before cross-validating, which let the test flowers influence the embedding. No labels were used in that step, but I replaced it with the fit-inside-each-fold version above so the test fold is not involved in the fit.

Check with an iterative MDS

Because the assignment mentions fitting MDS iteratively, I also ran scikit-learn's MDS (an iterative method called SMACOF) on the same geodesic distance matrix that Isomap computed (seed 572, 4 random starts; the best run took 85 iterations).

MeasureIsomap embeddingIterative MDS embedding
Raw stress (sum over pairs of squared distance error)1867.3169908.7291
Silhouette score using the true labels0.56000.5609

The pairwise distances of the two embeddings have a correlation of 0.9906, so the two embeddings are very similar even though the optimization differs. The iterative version has a lower raw stress, which is expected since it minimizes stress directly. The script is part5_mds_check.py.

Comparison: which is preferable?

On these criteria PCA is the better choice for this dataset. For compression, PCA with 2 components keeps 97.76% of the variance, and its pairwise distances correlate with the original 4D distances at 0.9984, against 0.9768 for Isomap. For classification, PCA reached 0.9733 and Isomap 0.9600 with seed 572, and over the 50 seeds the means were 0.9681 for PCA and 0.9459 for Isomap, with PCA ahead on 45 of the 50 seeds. PCA is also simpler: it does not depend on a neighbour graph, and it does not depend on the link scikit-learn adds to connect the graph. Isomap's silhouette score (0.5600, against 0.5344 for PCA and 0.5033 for the original data) is the one result in its favour. The average classification gap over the 50 seeds is about 2 points on 150 samples, so I would not call it large, and I only tested k = 3 neighbours.


Hand calculations

The worked-out solutions by hand for Part 1 (the first principal component and the two reconstruction errors) are in one PDF:

Open the hand calculations (PDF)


Code

All scripts are in this folder and need numpy, scipy, matplotlib and scikit-learn. iris.data (from the UCI link in the assignment) sits next to them, and each script is run with python3 from this folder. The plots are saved in media/.

FileWhat it does
common.pyloads iris.data, feature and class names, plot colors, the seed
part1_check.pynumpy check of the hand calculation in Part 1
part2_visualization.pyPart 2: Fig 1 to 3 and the per-class numbers
part3_pca.pyPart 3: PCA axes and Fig 4 to 6
part4_compression.pyPart 4: variance explained from the Frobenius norm, and Fig 7
part5_isomap.pyPart 5: Isomap with 3 nearest neighbours, Fig 8, and the comparison numbers
part5_cv_in_fold.pyPart 5: cross-validated classification with PCA and Isomap fit inside each fold
part5_mds_check.pyPart 5: iterative MDS on the Isomap geodesic distances, compared with Isomap
iris.datathe Iris data file from UCI

Larissa Rudenko - Fall 2026