Module 20 · Deep learning and neural networks · Lesson 65 of 66
Recognize handwritten digits
Train a neural network that reads handwritten numbers, the classic first deep learning project.
In this lesson · about 20 minutes
- Prepare image data for a neural network
- Train and score an MLPClassifier
- Read the same model written in Keras
The classic first project is MNIST: 70,000 photos of handwritten digits, 28 × 28 pixels each. It's too big to download and train on in a browser tab, so we'll use its small cousin from scikit-learn: 1,797 digits at 8 × 8 pixels. Each pixel is a number from 0 (white) to 16 (black), and each image is flattened into a row of 64 numbers.
Exercise
Scale and split
Neural networks learn best when inputs are small numbers. Make X, the pixels in digits.data divided by 16 so they run from 0 to 1. Then split X and digits.target into X_train, X_test, y_train and y_test with test_size=0.3 and random_state=101. End with X_train.shape.
Code that runs before yours
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split digits = load_digits()
Exercise
Train the network
Create MLPClassifier(hidden_layer_sizes=(32,), max_iter=500, random_state=101) called mlp: one hidden layer of 32 neurons. Fit it on the training data, then end with its accuracy on the test data, mlp.score(X_test, y_test). Training takes a few seconds.
Code that runs before yours
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split digits = load_digits() X = digits.data / 16 X_train, X_test, y_train, y_test = train_test_split(X, digits.target, test_size=0.3, random_state=101) from sklearn.neural_network import MLPClassifier
About 97 in 100 digits the network never saw are read correctly. Here's the same model in TensorFlow 2 with Keras, written for the full 28 × 28 MNIST. Keras adds the output layer explicitly: 10 neurons with softmax, which turns their outputs into 10 probabilities that add up to 1. MLPClassifier adds that layer for you.
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.Input(shape=(784,)), # 28 x 28 pixels, flattened
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax'),
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(X_train, y_train, epochs=10, batch_size=32)
model.evaluate(X_test, y_test)Where it went wrong
Exercises solved: 0 of 2
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.