Compress and Rebuild
Part of the Unsupervised Learning section of Coddy's Machine Learning journey. Lesson 31 of 51.
A scan's component scores are a recipe: start from the average scan, then add each pattern times its score. inverse_transform follows the recipe back to 64 pixels:
pca = PCA(n_components=10).fit(X)
codes = pca.transform(X) # 10 numbers per scan
rebuilt = pca.inverse_transform(codes) # 64 pixels againHere are three scans rebuilt from more and more numbers:
Few numbers give a blur near the average digit; each added component restores detail. Twenty numbers instead of 64 already read clearly.
Challenge
MediumA smart pen radios each digit as k PCA numbers, read by the program. What is lost?
- Fit PCA with
kcomponents onX. Compress all scans, then rebuild them intorebuilt. - Print the lines below; the error is the mean absolute difference from
X. - Draw the newest scan,
X[-1], onaxs[0]and its rebuild onaxs[1], bothgray_r. Show.
For 7:
Sent: 7 numbers per scan instead of 64
Average pixel error: 1.739and draws this. Coddy then describes your panels:
Try it yourself
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
# 1,797 scans of 64 pixels; the pen's newest scan is the last row
digits = load_digits()
X = digits.data
k = int(input())
# Don't change the lines below
fig, axs = plt.subplots(1, 2)
axs[0].set_title("Scan")
axs[1].set_title(f"Rebuilt from {k} numbers")
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unsupervised Learning
1Finding Groups
Learning Without LabelsMeasuring SimilarityK-Means by HandK-Means in scikit-learnRecap: Gym Members7PCA in Practice
Seeing 64 DimensionsComponents as PatternsCompress and RebuildPCA Before a ModelRecap: Face Scanner10Project: Digit Explorer
Look at the DigitsShrink with PCACluster the DigitsName the ClustersFind the Odd OnesPractice on your own: Online Python compiler