Menu
CoddyTech

Recap: Face Scanner

Part of the Unsupervised Learning section of Coddy's Machine Learning journey. Lesson 33 of 51.

challenge icon

Challenge

Medium

An 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.

  1. Fit PCA with k components. Print the share of the variance kept, as below.
  2. Draw face 0 on axs[0] and its rebuild from k numbers on axs[1], both with cmap="gray".
  3. Draw component 1 on axs[2] with cmap="gray_r". Show.

For another camera and 4:

Kept: 80.5% of the variance with 4 numbers per face

Three 16 by 16 pictures: a smiling face, its slightly smoother rebuild from 4 numbers, and component 1, a dark face shape on white

Coddy 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

Practice on your own: Online Python compiler