|
| 1 | +import numpy as np |
| 2 | +import keras |
| 3 | +from keras import layers |
| 4 | + |
| 5 | +# Model / data parameters |
| 6 | +num_classes = 10 |
| 7 | +input_shape = (28, 28, 1) |
| 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 |
| 13 | +x_train = x_train.astype("float32") / 255 |
| 14 | +x_test = x_test.astype("float32") / 255 |
| 15 | +# Make sure images have shape (28, 28, 1) |
| 16 | +x_train = np.expand_dims(x_train, -1) |
| 17 | +x_test = np.expand_dims(x_test, -1) |
| 18 | +print("x_train shape:", x_train.shape) |
| 19 | +print(x_train.shape[0], "train samples") |
| 20 | +print(x_test.shape[0], "test samples") |
| 21 | + |
| 22 | + |
| 23 | +# convert class vectors to binary class matrices |
| 24 | +y_train = keras.utils.to_categorical(y_train, num_classes) |
| 25 | +y_test = keras.utils.to_categorical(y_test, num_classes) |
| 26 | + |
| 27 | +model = keras.Sequential( |
| 28 | + [ |
| 29 | + keras.Input(shape=input_shape), |
| 30 | + layers.Conv2D(32, kernel_size=(3, 3), activation="relu"), |
| 31 | + layers.MaxPooling2D(pool_size=(2, 2)), |
| 32 | + layers.Conv2D(64, kernel_size=(3, 3), activation="relu"), |
| 33 | + layers.MaxPooling2D(pool_size=(2, 2)), |
| 34 | + layers.Flatten(), |
| 35 | + layers.Dropout(0.5), |
| 36 | + layers.Dense(num_classes, activation="softmax"), |
| 37 | + ] |
| 38 | +) |
| 39 | + |
| 40 | +model.summary() |
| 41 | + |
| 42 | +batch_size = 128 |
| 43 | +epochs = 15 |
| 44 | + |
| 45 | +model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"]) |
| 46 | + |
| 47 | +model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1) |
| 48 | + |
| 49 | + |
| 50 | +score = model.evaluate(x_test, y_test, verbose=0) |
| 51 | +print("Test loss:", score[0]) |
| 52 | +print("Test accuracy:", score[1]) |
0 commit comments