The Hello World of Deep Learning
In this lesson you will build a network that looks at pictures of handwritten digits and tells which digit it is, from 0 to 9. The data is called MNIST, and it contains 70,000 small 28 x 28 grayscale images.
Step 1: Load the Data
python
import keras
from keras import layers
import numpy as np
import matplotlib.pyplot as plt
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
print(x_train.shape) # (60000, 28, 28)
print(y_train.shape) # (60000,)
print(y_train[:10]) # [5 0 4 1 9 2 1 3 1 4]
There are 60,000 training images and 10,000 test images. Each label is the number written on the image.
Step 2: Look at an Image
python
plt.imshow(x_train[0], cmap="gray")
plt.title(f"Label: {y_train[0]}")
plt.axis("off")
plt.show()
Step 3: Preprocess
Pixel values go from 0 to 255. Neural networks prefer small numbers, so we scale them to be between 0 and 1.
python
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
Step 4: Build the Model
python
model = keras.Sequential([
keras.Input(shape=(28, 28)), # input: 28 x 28 pixels
layers.Flatten(), # turn the grid into 784 numbers
layers.Dense(128, activation="relu"), # hidden layer with 128 neurons
layers.Dense(10, activation="softmax") # output: 10 probabilities
])
model.summary()
| Layer | What it does |
Input | Tells the model the shape of one sample |
Flatten | 28 x 28 grid becomes a list of 784 numbers |
Dense(128, relu) | 128 neurons that learn patterns |
Dense(10, softmax) | One probability per digit |
Step 5: Compile
python
model.compile(
optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
Step 6: Train
python
history = model.fit(
x_train, y_train,
epochs=5,
batch_size=32,
validation_split=0.1
)
Result
Epoch 1/5 ... accuracy: 0.92. By epoch 5 the accuracy is around 0.98 on the training data.
Step 7: Evaluate on Test Data
python
test_loss, test_acc = model.evaluate(x_test, y_test)
print("Test accuracy:", test_acc) # around 0.97 to 0.98
Step 8: Make Predictions
python
predictions = model.predict(x_test[:5])
print(np.argmax(predictions, axis=1)) # predicted digits
print(y_test[:5]) # real digits
Result
Both lines print the same digits, for example 7 2 1 0 4.
Congratulations! You have trained a neural network that recognizes handwriting with about 97 percent accuracy using only a few lines of code.
Common Errors
| Error | Reason |
| Shape mismatch | Input shape does not match the data. Print x_train.shape |
| Accuracy stays near 10 percent | You forgot to scale the pixels, or the labels are wrong |
Unknown loss | Typo in the loss name |
Conclusion
You built, trained and tested a real neural network. All later projects follow the same steps: load data, preprocess, build, compile, fit, evaluate and predict.
Quick Summary: Load MNIST, scale to 0-1, build Flatten + Dense layers, compile with Adam, fit, evaluate and predict.