Attend the Women in ML Symposium on December 7 Register now

TensorFlow 2 quickstart for beginners

Stay organized with collections Save and categorize content based on your preferences.

View on 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. Run all the notebook code cells: Select Runtime > Run all.

Set up TensorFlow

Import TensorFlow into your program to get started:

import tensorflow as tf
print("TensorFlow version:", tf.__version__)
TensorFlow version: 2.8.0-rc1

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. Convert 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 by stacking layers.

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),

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.2760778 , -0.39324787, -0.17098302,  1.2016621 , -0.03416392,
         0.5461229 , -0.7203061 , -0.41886678, -0.59480035, -0.7580608 ]],

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

array([[0.11960829, 0.06124588, 0.0764901 , 0.30181262, 0.08770514,
        0.15668967, 0.04416083, 0.05969675, 0.05006609, 0.04252464]],

Define a loss function for training using losses.SparseCategoricalCrossentropy, which takes a vector of logits and a True index and returns a scalar loss for each example.

loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)

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 method to adjust your model parameters and minimize the loss:, y_train, epochs=5)
Epoch 1/5
1875/1875 [==============================] - 4s 2ms/step - loss: 0.2950 - accuracy: 0.9143
Epoch 2/5
1875/1875 [==============================] - 3s 2ms/step - loss: 0.1451 - accuracy: 0.9567
Epoch 3/5
1875/1875 [==============================] - 4s 2ms/step - loss: 0.1080 - accuracy: 0.9668
Epoch 4/5
1875/1875 [==============================] - 4s 2ms/step - loss: 0.0906 - accuracy: 0.9717
Epoch 5/5
1875/1875 [==============================] - 4s 2ms/step - loss: 0.0749 - accuracy: 0.9761
<keras.callbacks.History at 0x7f062c606850>

The Model.evaluate method checks the models performance, usually on a "Validation-set" or "Test-set".

model.evaluate(x_test,  y_test, verbose=2)
313/313 - 1s - loss: 0.0783 - accuracy: 0.9755 - 588ms/epoch - 2ms/step
[0.07825208455324173, 0.9754999876022339]

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.72807270e-08, 2.42517650e-08, 7.75602894e-06, 1.28684027e-04,
        7.66215633e-11, 3.54162950e-07, 3.04894151e-14, 9.99857187e-01,
        2.32766553e-08, 5.97762892e-06],
       [7.37396704e-08, 4.73638036e-04, 9.99523997e-01, 7.20633352e-07,
        4.54133671e-17, 1.42298268e-06, 5.96959016e-09, 1.23534145e-13,
        7.77225608e-08, 6.98619169e-16],
       [1.95462448e-07, 9.99295831e-01, 1.02249986e-04, 1.86699708e-05,
        5.65737491e-06, 1.12115902e-06, 5.32719559e-06, 5.22767776e-04,
        4.79981136e-05, 1.76624681e-07],
       [9.99649286e-01, 1.80224735e-09, 3.73612856e-05, 1.52324446e-07,
        1.30824594e-06, 2.82781020e-05, 6.99703523e-05, 3.30940424e-07,
        2.13184350e-07, 2.13106396e-04],
       [1.53770895e-06, 1.72272063e-08, 1.98980865e-06, 3.97882580e-08,
        9.97192323e-01, 1.10544443e-05, 1.54713348e-06, 2.81727880e-05,
        3.48721733e-06, 2.75991508e-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.