Lab 3 of 5about 30 minutes
A thousand digits, no loop
It uses what you learned in NumPy arrays and Vectorization and broadcasting.
Start here
Run itThe handwritten digits from the videos. They come with scikit-learn, so nothing is downloaded.
1The stack
Run itFrom NumPy arrays
Run the cell. It shows the stack's shape.
Three numbers, three sides: 1,797 pictures, then 8 rows, then 8 columns in each picture.
2The first ten
Your turnFrom NumPy arrays
Keep the first ten pictures in first_ten, with one slice.
Hint
A slice goes from its first position up to its second, and the second is not taken.
One way to do it
first_ten = images[0:10]
first_ten.shape3The last picture
Your turnFrom NumPy arrays
Try images[1797]. NumPy stops: IndexError: index 1797 is out of bounds for axis 0 with size 1797. Axis 0 is the first side, the pictures. Keep the last picture in last.
Hint
Size 1797 means the positions go from 0 to one less than that.
One way to do it
last = images[1796]
last.shape4Ink from 0 to 1
Your turnFrom Vectorization and broadcasting
Each number says how dark a square is, from 0 to 16. Models often want them from 0 to 1. Divide every number of every picture by 16, in one line and with no loop. Keep the result in scaled.
Hint
Write the sum as if images were one number.
One way to do it
scaled = images / 16
scaled.max()5The average picture, taken away
Your turnFrom NumPy arrays and Vectorization and broadcasting
scaled.mean(axis=0) is new: it takes the average down the first side, so the 1,797 pictures become one average picture, 8 by 8. Take it away from every picture. Before you run it, line the two shapes up on the right: do they fit?
Hint
NumPy repeats the smaller array to fit. You write only the subtraction.
One way to do it
average = scaled.mean(axis=0)
centered = scaled - average
centered.shape6Each picture's own ink
On your ownFrom Vectorization and broadcasting
Some people write darker than others. Here is how dark each picture is on average, one number for each picture. Take each picture's own number away from its 64 squares, and keep the result in evened. scaled - brightness stops: line the shapes up on the right and see why. reshape is new: brightness.reshape(1797, 1, 1) gives the same numbers a new shape.
brightness = scaled.mean(axis=(1, 2))
Hint
Lined up on the right, (1797,) sits under the columns. It has to sit under the pictures, with a 1 for the rows and a 1 for the columns.
One way to do it
brightness = scaled.mean(axis=(1, 2))
evened = scaled - brightness.reshape(1797, 1, 1)
evened.shapeRun on Pyodide 314, Python 3.14, NumPy 2.4 and scikit-learn 1.8. Checked on .
