![]() |
![]() |
![]() |
![]() |
This short introduction uses Keras to:
- Load a prebuilt dataset.
- Build a neural network machine learning model that classifies images.
- Train this neural network.
- Evaluate the accuracy of the model.
This tutorial is a Google Colaboratory notebook. Python programs are run directly in the browser—a great way to learn and use TensorFlow. To follow this tutorial, run the notebook in Google Colab by clicking the button at the top of this page.
- In Colab, connect to a Python runtime: At the top-right of the menu bar, select CONNECT.
- To run all the code in the notebook, select Runtime > Run all. To run the code cells one at a time, hover over each cell and select the Run cell icon.
Set up TensorFlow
Import TensorFlow into your program to get started:
import tensorflow as tf
print("TensorFlow version:", tf.__version__)
2023-11-16 02:20:34.135440: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:9261] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered 2023-11-16 02:20:34.135478: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:607] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered 2023-11-16 02:20:34.136990: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1515] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered TensorFlow version: 2.15.0
If you are following along in your own development environment, rather than Colab, see the install guide for setting up TensorFlow for development.
Load a dataset
Load and prepare the MNIST dataset. The pixel values of the images range from 0 through 255. Scale these values to a range of 0 to 1 by dividing the values by 255.0
. This also converts the sample data from integers to floating-point numbers:
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11490434/11490434 [==============================] - 0s 0us/step
Build a machine learning model
Build a tf.keras.Sequential
model:
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10)
])
Sequential
is useful for stacking layers where each layer has one input tensor and one output tensor. Layers are functions with a known mathematical structure that can be reused and have trainable variables. Most TensorFlow models are composed of layers. This model uses the Flatten
, Dense
, and Dropout
layers.
For each example, the model returns a vector of logits or log-odds scores, one for each class.
predictions = model(x_train[:1]).numpy()
predictions
array([[-0.00594383, 0.45658916, 0.10220155, -0.34953278, 0.46833006, 0.074406 , 0.2764801 , 0.11277628, -0.29951403, 0.1871729 ]], dtype=float32)
The tf.nn.softmax
function converts these logits to probabilities for each class:
tf.nn.softmax(predictions).numpy()
array([[0.08685794, 0.13793837, 0.09677796, 0.06160142, 0.13956742, 0.09412502, 0.11520325, 0.0978068 , 0.06476101, 0.10536081]], dtype=float32)
Define a loss function for training using losses.SparseCategoricalCrossentropy
:
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
The loss function takes a vector of ground truth values and a vector of logits and returns a scalar loss for each example. This loss is equal to the negative log probability of the true class: The loss is zero if the model is sure of the correct class.
This untrained model gives probabilities close to random (1/10 for each class), so the initial loss should be close to -tf.math.log(1/10) ~= 2.3
.
loss_fn(y_train[:1], predictions).numpy()
2.3631315
Before you start training, configure and compile the model using Keras Model.compile
. Set the optimizer
class to adam
, set the loss
to the loss_fn
function you defined earlier, and specify a metric to be evaluated for the model by setting the metrics
parameter to accuracy
.
model.compile(optimizer='adam',
loss=loss_fn,
metrics=['accuracy'])
Train and evaluate your model
Use the Model.fit
method to adjust your model parameters and minimize the loss:
model.fit(x_train, y_train, epochs=5)
Epoch 1/5 WARNING: All log messages before absl::InitializeLog() is called are written to STDERR I0000 00:00:1700101241.308881 9962 device_compiler.h:186] Compiled cluster using XLA! This line is logged at most once for the lifetime of the process. 1875/1875 [==============================] - 6s 2ms/step - loss: 0.2977 - accuracy: 0.9152 Epoch 2/5 1875/1875 [==============================] - 4s 2ms/step - loss: 0.1452 - accuracy: 0.9572 Epoch 3/5 1875/1875 [==============================] - 4s 2ms/step - loss: 0.1091 - accuracy: 0.9671 Epoch 4/5 1875/1875 [==============================] - 4s 2ms/step - loss: 0.0888 - accuracy: 0.9736 Epoch 5/5 1875/1875 [==============================] - 4s 2ms/step - loss: 0.0762 - accuracy: 0.9760 <keras.src.callbacks.History at 0x7efba0127d00>
The Model.evaluate
method checks the model's performance, usually on a validation set or test set.
model.evaluate(x_test, y_test, verbose=2)
313/313 - 1s - loss: 0.0778 - accuracy: 0.9752 - 584ms/epoch - 2ms/step [0.07776274532079697, 0.9751999974250793]
The image classifier is now trained to ~98% accuracy on this dataset. To learn more, read the TensorFlow tutorials.
If you want your model to return a probability, you can wrap the trained model, and attach the softmax to it:
probability_model = tf.keras.Sequential([
model,
tf.keras.layers.Softmax()
])
probability_model(x_test[:5])
<tf.Tensor: shape=(5, 10), dtype=float32, numpy= array([[2.6984657e-07, 3.8002440e-08, 1.6746913e-05, 1.0695006e-04, 1.1966110e-10, 2.5961143e-07, 8.1565288e-13, 9.9987197e-01, 1.0326594e-06, 2.8262818e-06], [1.3999164e-07, 5.5667624e-06, 9.9996352e-01, 2.4345095e-06, 1.7454881e-17, 2.8163922e-05, 4.7398025e-08, 1.9670790e-15, 1.7659848e-07, 2.6264062e-14], [3.0009883e-07, 9.9881589e-01, 2.4900693e-05, 1.1475331e-06, 2.0097617e-05, 1.5349242e-05, 5.1976604e-05, 6.3451822e-04, 4.3167319e-04, 4.1721478e-06], [9.9992681e-01, 2.3041305e-10, 3.7171503e-05, 1.1600308e-07, 8.1849976e-09, 1.7707794e-06, 3.2530028e-05, 7.4367080e-07, 1.2220231e-07, 7.3985012e-07], [2.4092253e-06, 2.3410928e-08, 4.2358351e-05, 1.2393063e-07, 9.9869967e-01, 4.2786400e-05, 1.6083415e-05, 5.3349639e-05, 1.4218396e-05, 1.1290688e-03]], dtype=float32)>
Conclusion
Congratulations! You have trained a machine learning model using a prebuilt dataset using the Keras API.
For more examples of using Keras, check out the tutorials. To learn more about building models with Keras, read the guides. If you want learn more about loading and preparing data, see the tutorials on image data loading or CSV data loading.