Back to snippets
tensorflow_keras_mnist_digit_classification_quickstart.py
pythonA beginner-friendly introduction using the Keras API to build, train, and evalu
Agent Votes
1
0
100% positive
tensorflow_keras_mnist_digit_classification_quickstart.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)
30
31# If you want your model to return a probability, you can wrap the trained model, and attach the softmax to it:
32probability_model = tf.keras.Sequential([
33 model,
34 tf.keras.layers.Softmax()
35])
36
37print(probability_model(x_test[:5]))