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. Build a neural network that classifies images.
  2. Train this neural network.
  3. And, finally, evaluate the accuracy of the model.

This is a Google Colaboratory notebook file. 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.

Download and install TensorFlow 2. Import TensorFlow into your program:

import tensorflow as tf

Load and prepare the MNIST dataset. Convert the samples 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 the tf.keras.Sequential model by stacking layers. Choose an optimizer and loss function for training:

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([[ 8.1478250e-01, -4.9710822e-01, -4.4540316e-04,  8.0338269e-02,
        -1.2498328e-01, -2.8269893e-01,  4.8158792e-01, -2.3113336e-01,
        -6.4444810e-02,  2.9273060e-01]], dtype=float32)

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

array([[0.2003022 , 0.05394346, 0.08864142, 0.09609938, 0.07826194,
        0.06684294, 0.14354272, 0.07038016, 0.08314615, 0.11883967]],

The losses.SparseCategoricalCrossentropy loss 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: It 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()

The Model.fit method adjusts the model parameters to minimize the loss:

model.fit(x_train, y_train, epochs=5)
Epoch 1/5
1875/1875 [==============================] - 3s 1ms/step - loss: 0.2913 - accuracy: 0.9147
Epoch 2/5
1875/1875 [==============================] - 3s 1ms/step - loss: 0.1418 - accuracy: 0.9584
Epoch 3/5
1875/1875 [==============================] - 3s 1ms/step - loss: 0.1058 - accuracy: 0.9681
Epoch 4/5
1875/1875 [==============================] - 3s 1ms/step - loss: 0.0879 - accuracy: 0.9730
Epoch 5/5
1875/1875 [==============================] - 3s 1ms/step - loss: 0.0744 - accuracy: 0.9765
<tensorflow.python.keras.callbacks.History at 0x7fc99a051290>

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 - 0s - loss: 0.0737 - accuracy: 0.9784
[0.07365398108959198, 0.9783999919891357]

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.7845143e-09, 6.2416250e-09, 8.8993971e-07, 5.0938579e-05,
        6.9239370e-10, 9.1531788e-08, 3.0702079e-12, 9.9993479e-01,
        1.6381224e-06, 1.1627582e-05],
       [1.6608839e-08, 6.1237602e-04, 9.9933952e-01, 4.5319266e-05,
        4.2082616e-14, 6.8845372e-07, 1.2797722e-08, 1.6431847e-12,
        2.0782168e-06, 2.8262946e-11],
       [1.3514825e-06, 9.9640971e-01, 1.8868307e-04, 2.4645233e-05,
        8.3467271e-04, 1.7597053e-05, 5.1044153e-05, 1.7571129e-03,
        6.8748201e-04, 2.7744498e-05],
       [9.9969614e-01, 3.3471906e-08, 1.3097884e-05, 3.4203765e-08,
        2.6330403e-07, 6.6318894e-06, 2.1209409e-04, 4.3179925e-06,
        1.5615402e-07, 6.7310575e-05],
       [4.4438386e-07, 5.8649330e-09, 6.7045465e-07, 6.9524458e-10,
        9.9840516e-01, 1.0503891e-07, 3.2713297e-07, 3.2584390e-05,
        3.4801921e-08, 1.5606619e-03]], dtype=float32)>