CS 460G Midterm Hub / Notebooks / Dimensionality Reduction
Python notebook · Copy of dimensionality-reduction.ipynb

Dimensionality Reduction

PCA on tabular, image and volumetric data, plus an autoencoder

practice nbQ6 material

Four applications of one method, which is why it is the best notebook for understanding what PCA is actually for.

Part 1 — breast cancer, 569×30

Load and check

breast_db = datasets.load_breast_cancer()
breast_Xhd = breast_db['data']      # (569, 30)
labels     = breast_db['target']

30 features: ten measurements (radius, texture, perimeter, area, smoothness, compactness, concavity, concave points, symmetry, fractal dimension) each in three versions — mean, standard error, and "worst".

Baseline classifier

X_train, X_test, y_train, y_test = train_test_split(breast_Xhd, labels, test_size=0.25)
KN_model = KNeighborsClassifier().fit(X_train, y_train)
print('Accuracy: ', metrics.accuracy_score(KN_prediction, y_test).round(2))
# 0.93

Remember 0.93 — this is the number PCA must beat.

Scale, then PCA

from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

scaler = StandardScaler()
breast_Xhd_scaled = scaler.fit_transform(breast_Xhd)

pca = PCA(n_components=5)
breast_Xld = pca.fit_transform(breast_Xhd_scaled)
breast_Xld.shape      # (569, 5)

Why StandardScaler first, and why it is not optional: PCA maximises variance, and variance is scale-dependent. area ranges into the thousands while smoothness ranges into hundredths — un-standardised, PC1 would simply be area, and the other 29 dimensions would vanish into rounding error. The scaler gives every feature unit variance so the decomposition is about correlation structure rather than units.

fit_transform vs transform: fit_transform on the training data learns the mean/std and applies them. On test data you must call transform only — fitting again would leak test statistics into the transformation.

Explained variance

expl_var_rat = pca.explained_variance_ratio_
plt.bar(range(1,6), expl_var_rat, label='individual explained variance')
plt.step(range(1,6), np.cumsum(pca.explained_variance_ratio_), label='cumulative')

Finding: about 90% of the variance is captured by 5 components out of 30. And separately, "about 50% of the features hardly provide any information" — the individual bars for later components are near zero.

Choosing k properly

pca = PCA().fit(breast_Xhd_scaled)          # fit all 30
plt.plot(np.cumsum(pca.explained_variance_ratio_))

Fitting with no n_components keeps all of them, so the cumulative curve shows you where the elbow is. pca.explained_variance_ratio_ has length 30 here.

The same thing from scratch

cov = np.cov(breast_Xhd_scaled.T)
eval, evec = np.linalg.eig(cov)
eval_rat = [i/eval.sum() for i in eval]
plt.plot(np.cumsum(eval_rat))

Why this cell exists: to prove that PCA is nothing but an eigendecomposition of the covariance matrix. .T because np.cov expects variables in columns. The two curves overlap exactly — that is the demonstration.

Note: np.linalg.eig does not sort the eigenvalues, and for a symmetric matrix np.linalg.eigh is both faster and numerically safer. The plot works here only because cumsum of an unsorted spectrum is still monotone in the count — but the components are not in variance order. Assignment 2 explicitly requires sorting.

Classify on the reduced data

X_train, X_test, y_train, y_test = train_test_split(breast_Xld, labels, test_size=0.25)
KN_model = KNeighborsClassifier().fit(X_train, y_train)
print('Accuracy: ', metrics.accuracy_score(KN_prediction, y_test).round(2))
# 0.97
ModelFeaturesAccuracy
KNN on raw data300.93
KNN after PCA50.97

The question this answers: "why did accuracy go UP after throwing away 25 dimensions?" Because those 25 dimensions are mostly noise and near-duplicates of the first 5 — the 30 features are ten measurements repeated three ways, so they are heavily correlated. KNN's Euclidean distance sums over all 30 coordinates, so 25 noisy directions dilute the 5 informative ones and the nearest neighbour is often the wrong point. Projecting onto 5 components removes that dilution: it is denoising, not just compression. The lesson generalises — dimensionality reduction helps when the discarded dimensions carry more noise than signal.

Part 2 — 8×8 digits

digit_data = datasets.load_digits()
images = digit_data['images']    # (1797, 8, 8)
labels = digit_data['target']
pca = PCA(n_components=2)
images_ld = pca.fit_transform(images.reshape(-1, 8*8))
# (1797, 2)

The reshape (-1, 64) flattens each image to a feature vector — 64 pixel intensities. That is the "feature extraction" step: the pixels are the features.

Then KNN on 2 components:

print('Accuracy: ', metrics.accuracy_score(KN_prediction, y_test).round(2))
# 0.61

0.61 from 2 dimensions is remarkably high and it is the point: the first two principal components already separate most digits, because the dominant variance directions in handwritten digits correspond to stroke weight and slant. But it is far below the ~97% achievable with all 64, so it is also the lower bound that motivates increasing $k$.

Part 3 — MRI compression

import nibabel as nib
img_nii = nib.load(os.path.join(data_path, 'example4d.nii.gz'))
img_3d = img_nii.get_fdata()[:,:,:,0]
print('MRI image shape: ', img_3d.shape)      # (128, 96, 24)

Compressing one slice

img_3d = img_3d.transpose(2,1,0)     # (24, 96, 128)
pca = PCA(n_components=16)
img_com = pca.fit_transform(img_3d[10])     # (96, 16)
img_recon = pca.inverse_transform(img_com)
print('MSE: ', np.mean((img_3d[10]-img_recon)2))   # 533.18

96×128 = 12,288 numbers reduced to 96×16 = 1,536** — an 8× compression — with a reconstruction error you can see on the error map.

Compressing the whole volume

pca = PCA(n_components=16)
img_3dcom = pca.fit_transform(img_3d.reshape(-1, 96*128))    # (24, 16)
img_3drecon = pca.inverse_transform(img_3dcom).reshape(-1,96,128)
print('MSE: ', np.mean((img_3d[10]-img_3drecon[10])2))     # 180.98
CompressionShape reducedMSE
Single slice96×128 → 96×16533.18
Whole volume24×2304 → 24×16180.98

Why is the whole-volume compression better, with the same 16 components? Because the components are shared across all 24 slices. Fitting on the whole volume gives the eigensystem 24× more data to estimate each component, and the components then capture structure common to every slice rather than noise specific to one. Same latent dimension, better estimate — a direct illustration of the bias-variance argument for more data.

On the reshape(-1, 96*128) trick:** it treats each slice as one sample with 12,288 features, so PCA runs across the 24 slices. That is the right axis if the goal is to find directions that describe the volume.

Part 4 — the autoencoder

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(64, 10)     # encoder  64 -> 10
        self.fc2 = nn.Linear(10, 64)     # decoder  10 -> 64
    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = self.fc2(x)                  # no activation on the output
        return x

Note the architecture: bottleneck 64 → 10 → 64, no non-linearity on the output (the target is the input, in [0,16] pixel units, not a probability).

criterion = nn.MSELoss()
optimizer = torch.optim.Adam(net.parameters(), lr=0.001, weight_decay=1e-2)
for epoch in range(50):
    for i, data in enumerate(trainloader):   # data is the input only
        optimizer.zero_grad()
        outputs = net(data)
        loss = criterion(outputs, data)      # target IS the input
        loss.backward(); optimizer.step()

The one line that defines an autoencoder: loss = criterion(outputs, data). The target is the input. That is why it is self-supervised.

plt.subplot(131); plt.imshow(inputs.reshape(-1,8,8)[0], 'gray')
plt.subplot(132); plt.imshow(outputs.reshape(-1,8,8)[0].data.numpy(), 'gray')
plt.subplot(133); plt.imshow(x[0]-x_hat[0].data.numpy(), 'gray')

Three panels: input, reconstruction, residual. The residual image is the honest measure — if it looks like noise, the autoencoder captured everything structured; if it shows the digit's outline, it failed to.

Note the bug in the training loop: running_loss = 0.0 is inside the for i loop rather than outside, so the printed running average is over a single batch. Cosmetic, but it is exactly the kind of thing a "what is wrong with this cell?" question targets.

The comparison

PCAAutoencoder
Linearitylinearnon-linear (with ReLU)
Solutionclosed formgradient descent
Componentsorthogonal, variance-orderedunconstrained
Data neededcovariance onlymany samples
Compression shown here30 → 5 (90% var)64 → 10
Reconstruction errorreported as MSEreported as MSE

The lecture's claim, demonstrated by the architecture: with linear encoder and decoder, the autoencoder's optimum is PCA. The ReLU is what makes this one non-linear.