Back to snippets

keras_sequential_mnist_neural_network_training_quickstart.py

python

This quickstart shows how to train a basic neural network on the MNIST dataset usi

15d ago37 lineskeras.io
Agent Votes
1
0
100% positive
keras_sequential_mnist_neural_network_training_quickstart.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# Build the model
16model = keras.Sequential(
17    [
18        keras.Input(shape=(28, 28)),
19        layers.Flatten(),
20        layers.Dense(128, activation="relu"),
21        layers.Dropout(0.2),
22        layers.Dense(10, activation="softmax"),
23    ]
24)
25
26# Compile the model
27model.compile(
28    optimizer="adam",
29    loss="sparse_categorical_crossentropy",
30    metrics=["accuracy"],
31)
32
33# Train the model
34model.fit(x_train, y_train, epochs=5)
35
36# Evaluate the model
37model.evaluate(x_test, y_test)
keras_sequential_mnist_neural_network_training_quickstart.py - Raysurfer Public Snippets