TensorFlow 2 quickstart for beginners

View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook

This short introduction uses Keras to:

  1. Load a prebuilt dataset.
  2. Build a neural network machine learning model that classifies images.
  3. Train this neural network.
  4. 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.

  1. In Colab, connect to a Python runtime: At the top-right of the menu bar, select CONNECT.
  2. 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.

Run cell icon

Set up TensorFlow

Import TensorFlow into your program to get started:

import tensorflow as tf
print("TensorFlow version:", tf.__version__)
2024-07-13 06:52:18.998540: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:479] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
2024-07-13 06:52:19.024905: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:10575] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
2024-07-13 06:52:19.024943: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1442] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
TensorFlow version: 2.16.2

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'),
/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.

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()
array([[-0.16857487, -0.01702446, -0.18800262, -0.29049426, -0.1497654 ,
         0.01135813, -0.13169414,  0.28695202,  0.37672728,  0.13688533]],

The tf.nn.softmax function converts these logits to probabilities for each class:

array([[0.08373321, 0.09743506, 0.08212215, 0.07412229, 0.08532309,
        0.10024013, 0.086879  , 0.13204761, 0.14445063, 0.11364685]],

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()

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.


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:1720853545.131188  523089 service.cc:145] XLA service 0x7fb588008030 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
I0000 00:00:1720853545.131230  523089 service.cc:153]   StreamExecutor device (0): Tesla T4, Compute Capability 7.5
I0000 00:00:1720853545.131234  523089 service.cc:153]   StreamExecutor device (1): Tesla T4, Compute Capability 7.5
I0000 00:00:1720853545.131237  523089 service.cc:153]   StreamExecutor device (2): Tesla T4, Compute Capability 7.5
I0000 00:00:1720853545.131240  523089 service.cc:153]   StreamExecutor device (3): Tesla T4, Compute Capability 7.5
116/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.5960 - loss: 1.3751
I0000 00:00:1720853546.834081  523089 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 5s 1ms/step - accuracy: 0.8633 - loss: 0.4777
Epoch 2/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.9561 - loss: 0.1461
Epoch 3/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.9682 - loss: 0.1073
Epoch 4/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.9744 - loss: 0.0848
Epoch 5/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.9772 - loss: 0.0711
<keras.src.callbacks.history.History at 0x7fb750d4bc40>

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 - 3ms/step - accuracy: 0.9766 - loss: 0.0709
[0.07090681046247482, 0.9765999913215637]

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([
<tf.Tensor: shape=(5, 10), dtype=float32, numpy=
array([[1.2273183e-07, 8.7016083e-09, 5.6712506e-06, 1.6725733e-04,
        3.8532035e-11, 3.1167556e-07, 3.1886015e-13, 9.9981803e-01,
        6.9700377e-08, 8.4526291e-06],
       [3.8318063e-10, 5.3196814e-05, 9.9994433e-01, 1.2887319e-06,
        6.4013896e-16, 1.0868150e-06, 1.7267263e-09, 9.1941645e-14,
        1.7351501e-07, 1.2004752e-16],
       [8.1174614e-09, 9.9988675e-01, 2.9579714e-05, 1.9076538e-06,
        5.8524206e-06, 1.8120238e-06, 8.6344735e-06, 3.9572973e-05,
        2.5875805e-05, 3.4755587e-08],
       [9.9995661e-01, 1.8822339e-09, 1.1518332e-06, 4.0551839e-08,
        1.0557898e-08, 3.4465447e-07, 2.8761485e-06, 3.4590674e-05,
        1.2326135e-09, 4.4350991e-06],
       [2.7767928e-07, 4.2751531e-09, 3.1395750e-06, 3.2061170e-08,
        9.9942112e-01, 1.6970212e-07, 1.6067910e-06, 8.6861517e-05,
        7.6640458e-07, 4.8607125e-04]], dtype=float32)>


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.