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__)
TensorFlow version: 2.16.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'),
/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.05355236, -0.38770902, -0.3950655 ,  0.56203324,  0.4008786 ,
         0.49330375, -0.90321934,  0.59196687,  0.01143059,  0.22930913]],

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

array([[0.08960238, 0.05763445, 0.05721202, 0.14898755, 0.12681231,
        0.13909167, 0.03441905, 0.15351471, 0.08590656, 0.10681929]],

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:1718852934.550133  123430 service.cc:145] XLA service 0x7f46f8008490 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
I0000 00:00:1718852934.550178  123430 service.cc:153]   StreamExecutor device (0): Tesla T4, Compute Capability 7.5
I0000 00:00:1718852934.550182  123430 service.cc:153]   StreamExecutor device (1): Tesla T4, Compute Capability 7.5
I0000 00:00:1718852934.550185  123430 service.cc:153]   StreamExecutor device (2): Tesla T4, Compute Capability 7.5
I0000 00:00:1718852934.550188  123430 service.cc:153]   StreamExecutor device (3): Tesla T4, Compute Capability 7.5
123/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.6001 - loss: 1.3087
I0000 00:00:1718852936.305291  123430 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.8594 - loss: 0.4784
Epoch 2/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.9547 - loss: 0.1534
Epoch 3/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.9675 - loss: 0.1083
Epoch 4/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.9726 - loss: 0.0904
Epoch 5/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.9763 - loss: 0.0763
<keras.src.callbacks.history.History at 0x7f48bc65c490>

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.9748 - loss: 0.0787
[0.07870220392942429, 0.9747999906539917]

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([[2.91052094e-09, 3.96534006e-09, 6.78467643e-07, 8.73977551e-05,
        5.18356896e-13, 1.82879518e-07, 2.16092970e-15, 9.99908686e-01,
        2.68296674e-08, 2.98205100e-06],
       [2.17597274e-09, 6.68564326e-06, 9.99987841e-01, 4.92203208e-06,
        3.21570516e-18, 2.29850897e-07, 6.52481535e-09, 1.29564397e-11,
        3.02037677e-07, 1.33335285e-14],
       [3.33186918e-08, 9.99066412e-01, 6.12782824e-05, 8.50183551e-06,
        6.73282693e-06, 1.31535044e-05, 1.09100047e-05, 5.36171836e-04,
        2.95553473e-04, 1.24834935e-06],
       [9.99714792e-01, 1.18584387e-08, 1.68357928e-05, 2.36769938e-05,
        1.83483966e-08, 1.21934929e-04, 9.09337814e-07, 6.99243756e-05,
        9.75373382e-07, 5.08306694e-05],
       [5.53078689e-06, 1.68281780e-08, 4.75335810e-06, 1.23027505e-07,
        9.90775287e-01, 2.68993335e-06, 3.49692345e-06, 5.85925067e-04,
        3.44339173e-06, 8.61874036e-03]], 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.