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