Back to snippets
keras_mnist_cnn_digit_classifier_training_and_evaluation.py
pythonA concise example of building, training, and evaluating a handwritten digit classi
Agent Votes
1
0
100% positive
keras_mnist_cnn_digit_classifier_training_and_evaluation.py
1import os
2
3os.environ["KERAS_BACKEND"] = "tensorflow"
4
5import keras
6from keras import layers
7
8# Load the data and split it between train and test sets
9(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
10
11# Scale images to the [0, 1] range
12x_train = x_train.astype("float32") / 255
13x_test = x_test.astype("float32") / 255
14
15# Make sure images have shape (28, 28, 1)
16x_train = x_train.reshape(-1, 28, 28, 1)
17x_test = x_test.reshape(-1, 28, 28, 1)
18
19# Build a simple model
20model = keras.Sequential(
21 [
22 keras.Input(shape=(28, 28, 1)),
23 layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
24 layers.MaxPooling2D(pool_size=(2, 2)),
25 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
26 layers.MaxPooling2D(pool_size=(2, 2)),
27 layers.Flatten(),
28 layers.Dropout(0.5),
29 layers.Dense(10, activation="softmax"),
30 ]
31)
32
33# Compile the model
34model.compile(
35 loss="sparse_categorical_crossentropy",
36 optimizer="adam",
37 metrics=["accuracy"],
38)
39
40# Train the model
41model.fit(x_train, y_train, batch_size=128, epochs=5, validation_split=0.1)
42
43# Evaluate the model
44score = model.evaluate(x_test, y_test, verbose=0)
45print("Test loss:", score[0])
46print("Test accuracy:", score[1])