View on TensorFlow.org
|
Run in Google Colab
|
View source on GitHub
|
Download notebook
|
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__)
2025-12-01 08:02:22.500164: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:467] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered WARNING: All log messages before absl::InitializeLog() is called are written to STDERR E0000 00:00:1764576142.522758 338111 cuda_dnn.cc:8579] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered E0000 00:00:1764576142.530142 338111 cuda_blas.cc:1407] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered W0000 00:00:1764576142.548377 338111 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once. W0000 00:00:1764576142.548397 338111 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once. W0000 00:00:1764576142.548400 338111 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once. W0000 00:00:1764576142.548402 338111 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once. TensorFlow version: 2.19.1
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)
])
/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/keras/src/layers/reshaping/flatten.py:37: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead. super().__init__(**kwargs) I0000 00:00:1764576147.509395 338111 gpu_device.cc:2019] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 13638 MB memory: -> device: 0, name: Tesla T4, pci bus id: 0000:00:05.0, compute capability: 7.5 I0000 00:00:1764576147.511656 338111 gpu_device.cc:2019] Created device /job:localhost/replica:0/task:0/device:GPU:1 with 13756 MB memory: -> device: 1, name: Tesla T4, pci bus id: 0000:00:06.0, compute capability: 7.5 I0000 00:00:1764576147.513816 338111 gpu_device.cc:2019] Created device /job:localhost/replica:0/task:0/device:GPU:2 with 13756 MB memory: -> device: 2, name: Tesla T4, pci bus id: 0000:00:07.0, compute capability: 7.5 I0000 00:00:1764576147.515995 338111 gpu_device.cc:2019] Created device /job:localhost/replica:0/task:0/device:GPU:3 with 13756 MB memory: -> device: 3, name: Tesla T4, pci bus id: 0000:00:08.0, compute capability: 7.5
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([[ 1.0652735 , 0.31860358, 0.38654593, -0.08616059, 0.16579574,
-0.06400671, 0.20459843, 0.30348206, 0.1970461 , 0.23852463]],
dtype=float32)
The tf.nn.softmax function converts these logits to probabilities for each class:
tf.nn.softmax(predictions).numpy()
array([[0.20945455, 0.09926935, 0.10624833, 0.06622598, 0.08520236,
0.06770951, 0.08857341, 0.09777954, 0.08790699, 0.09162993]],
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()
np.float32(2.6925287)
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:1764576150.048155 338278 service.cc:152] XLA service 0x7fc8cc0085a0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices: I0000 00:00:1764576150.048189 338278 service.cc:160] StreamExecutor device (0): Tesla T4, Compute Capability 7.5 I0000 00:00:1764576150.048194 338278 service.cc:160] StreamExecutor device (1): Tesla T4, Compute Capability 7.5 I0000 00:00:1764576150.048197 338278 service.cc:160] StreamExecutor device (2): Tesla T4, Compute Capability 7.5 I0000 00:00:1764576150.048200 338278 service.cc:160] StreamExecutor device (3): Tesla T4, Compute Capability 7.5 I0000 00:00:1764576150.174527 338278 cuda_dnn.cc:529] Loaded cuDNN version 91600 78/1875 ━━━━━━━━━━━━━━━━━━━━ 3s 2ms/step - accuracy: 0.5801 - loss: 1.4763 I0000 00:00:1764576151.295412 338278 device_compiler.h:188] Compiled cluster using XLA! This line is logged at most once for the lifetime of the process. 1875/1875 ━━━━━━━━━━━━━━━━━━━━ 6s 2ms/step - accuracy: 0.8660 - loss: 0.4733 Epoch 2/5 1875/1875 ━━━━━━━━━━━━━━━━━━━━ 4s 2ms/step - accuracy: 0.9551 - loss: 0.1531 Epoch 3/5 1875/1875 ━━━━━━━━━━━━━━━━━━━━ 4s 2ms/step - accuracy: 0.9661 - loss: 0.1119 Epoch 4/5 1875/1875 ━━━━━━━━━━━━━━━━━━━━ 4s 2ms/step - accuracy: 0.9735 - loss: 0.0882 Epoch 5/5 1875/1875 ━━━━━━━━━━━━━━━━━━━━ 4s 2ms/step - accuracy: 0.9753 - loss: 0.0776 <keras.src.callbacks.history.History at 0x7fcaeb2cf730>
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 - 2s - 5ms/step - accuracy: 0.9760 - loss: 0.0757 [0.07565543800592422, 0.9760000109672546]
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.4434946e-07, 1.1456399e-08, 7.3768051e-06, 1.3915766e-03,
3.4680422e-10, 1.3050453e-07, 8.2537872e-15, 9.9852508e-01,
2.2094671e-06, 7.3493255e-05],
[1.0771681e-09, 5.1975966e-04, 9.9947685e-01, 2.9423047e-06,
3.1367036e-15, 3.0040022e-07, 2.4699354e-10, 2.2032635e-14,
1.3495290e-07, 1.9704436e-14],
[2.9444012e-08, 9.9942350e-01, 2.0147660e-05, 2.0294808e-06,
7.5237884e-05, 2.9112320e-07, 1.0166094e-06, 4.5162931e-04,
2.1575637e-05, 4.6531054e-06],
[9.9840659e-01, 2.7419750e-07, 9.3252771e-04, 6.5548193e-05,
1.0807683e-05, 3.3787364e-05, 1.8924232e-04, 1.9979423e-05,
4.1641229e-08, 3.4119995e-04],
[2.6805938e-06, 8.1671576e-09, 2.2592160e-06, 7.1955448e-08,
9.9796814e-01, 6.8931207e-08, 3.6518026e-07, 8.0973987e-05,
1.0743844e-06, 1.9442304e-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.
View on TensorFlow.org
Run in Google Colab
View source on GitHub
Download notebook