![]() |
![]() |
![]() |
![]() |
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-09-28 06:29:49.456687: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered 2023-09-28 06:29:49.456734: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered 2023-09-28 06:29:49.456765: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered TensorFlow version: 2.14.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
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)
])
2023-09-28 06:29:52.597977: W tensorflow/core/common_runtime/gpu/gpu_device.cc:2211] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform. Skipping registering GPU devices...
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.15671095, 0.34050667, -0.25447032, -0.21112242, 0.7873671 , -0.18945682, -0.24646667, 0.6270074 , 0.08861928, 0.30534467]], dtype=float32)
The tf.nn.softmax
function converts these logits to probabilities for each class:
tf.nn.softmax(predictions).numpy()
array([[0.07140099, 0.11739326, 0.06475121, 0.06761976, 0.18353215, 0.06910077, 0.06527154, 0.15633954, 0.09125356, 0.1133372 ]], 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.6721892
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 1875/1875 [==============================] - 4s 2ms/step - loss: 0.2948 - accuracy: 0.9143 Epoch 2/5 1875/1875 [==============================] - 4s 2ms/step - loss: 0.1417 - accuracy: 0.9578 Epoch 3/5 1875/1875 [==============================] - 4s 2ms/step - loss: 0.1069 - accuracy: 0.9681 Epoch 4/5 1875/1875 [==============================] - 4s 2ms/step - loss: 0.0880 - accuracy: 0.9730 Epoch 5/5 1875/1875 [==============================] - 4s 2ms/step - loss: 0.0742 - accuracy: 0.9770 <keras.src.callbacks.History at 0x7fecf828d850>
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 - 0s - loss: 0.0729 - accuracy: 0.9787 - 492ms/epoch - 2ms/step [0.07287172228097916, 0.9786999821662903]
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([[1.03351276e-07, 2.85029911e-09, 5.02803641e-06, 5.50961122e-05, 1.23595328e-10, 1.19249348e-08, 4.77126510e-14, 9.99937415e-01, 2.27301584e-07, 2.13070666e-06], [2.34906693e-07, 2.45156298e-05, 9.99972105e-01, 3.00236752e-06, 5.78938464e-15, 4.98024342e-08, 8.80144384e-08, 2.45729798e-14, 3.44698421e-08, 1.93634120e-14], [5.02443129e-07, 9.98976111e-01, 1.06956380e-04, 8.93202014e-06, 1.01850230e-04, 1.03944603e-05, 1.40470556e-05, 6.82640704e-04, 9.75138901e-05, 1.14052375e-06], [9.99968052e-01, 2.95201953e-11, 1.38824580e-05, 8.60544347e-09, 4.92009690e-07, 3.53923326e-07, 1.26023451e-06, 3.32718878e-06, 1.15352672e-09, 1.26930190e-05], [1.29522448e-06, 2.05570130e-10, 3.72917043e-06, 5.05625597e-10, 9.97583508e-01, 2.17012840e-07, 1.31777051e-05, 6.12040822e-05, 4.94766368e-07, 2.33642897e-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.