Recap: Face Scanner
Part of the Unsupervised Learning section of Coddy's Machine Learning journey. Lesson 33 of 51.
Challenge
MediumAn office door camera may keep only k numbers per face; the program reads k. The starter draws 300 faces of 16 by 16 pixels into X.
- Fit PCA with
kcomponents. Print the share of the variance kept, as below. - Draw face 0 on
axs[0]and its rebuild fromknumbers onaxs[1], both withcmap="gray". - Draw component 1 on
axs[2]withcmap="gray_r". Show.
For another camera and 4:
Kept: 80.5% of the variance with 4 numbers per faceCoddy then describes your three panels.
Try it yourself
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
# Draws count faces of 16 by 16 pixels: one flat row of 256 brightnesses (0 to 1) per face
def make_faces(count, seed):
rng = np.random.default_rng(seed)
cols, rows = np.meshgrid(np.arange(16), np.arange(16))
faces = []
for i in range(count):
light = rng.uniform(0.55, 0.95)
side = rng.uniform(-0.25, 0.25)
head = ((cols - 7.5) / 6.2) ** 2 + ((rows - 8) / 7.6) ** 2 < 1
face = head * (light + side * (cols - 7.5) / 7.5)
eye_row = rng.uniform(5, 7)
gap = rng.uniform(2.2, 3.6)
for eye_col in [7.5 - gap, 7.5 + gap]:
face = face - 0.7 * np.exp(-((cols - eye_col) ** 2 + (rows - eye_row) ** 2) / 1.2)
smile = rng.uniform(-2, 2)
mouth_row = 11.5 - smile * ((cols - 7.5) / 3.5) ** 2
mouth = np.exp(-((rows - mouth_row) ** 2) / 0.4) * (np.abs(cols - 7.5) < 3.6)
face = face - 0.6 * mouth + rng.normal(0, 0.04, size=(16, 16))
faces.append(np.clip(face, 0, 1).flatten())
return np.round(np.array(faces), 2)
# 300 faces the door camera saw, and how many numbers it may keep per face
X = make_faces(300, seed=7)
k = int(input())
# Don't change the lines below
fig, axs = plt.subplots(1, 3)
axs[0].set_title("Face")
axs[1].set_title(f"Rebuilt from {k}")
axs[2].set_title("Component 1")
# Write your code below
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