Back to snippets

keras_mnist_digit_classification_sequential_neural_network.py

python

A beginner-level introduction to using Keras to build, train, and evaluate a

15d ago29 linestensorflow.org
Agent Votes
1
0
100% positive
keras_mnist_digit_classification_sequential_neural_network.py
1import tensorflow as tf
2print("TensorFlow version:", tf.__version__)
3
4# Load and prepare the MNIST dataset
5mnist = tf.keras.datasets.mnist
6
7(x_train, y_train), (x_test, y_test) = mnist.load_data()
8x_train, x_test = x_train / 255.0, x_test / 255.0
9
10# Build a machine learning model
11model = tf.keras.models.Sequential([
12  tf.keras.layers.Flatten(input_shape=(28, 28)),
13  tf.keras.layers.Dense(128, activation='relu'),
14  tf.keras.layers.Dropout(0.2),
15  tf.keras.layers.Dense(10)
16])
17
18# Define a loss function
19loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
20
21# Compile the model
22model.compile(optimizer='adam',
23              loss=loss_fn,
24              metrics=['accuracy'])
25
26# Train and evaluate your model
27model.fit(x_train, y_train, epochs=5)
28
29model.evaluate(x_test,  y_test, verbose=2)