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:

from __future__ import absolute_import, division, print_function, unicode_literals


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'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10)
])

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
WARNING:tensorflow:Layer flatten is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2.  The layer has dtype float32 because it's dtype defaults to floatx.

If you intended to run this layer in float32, you can safely ignore this warning. If in doubt, this warning is likely only an issue if you are porting a TensorFlow 1.X model to TensorFlow 2.

To change all layers to have dtype float64 by default, call `tf.keras.backend.set_floatx('float64')`. To change just this layer, pass dtype='float64' to the layer constructor. If you are the author of this layer, you can disable autocasting by passing autocast=False to the base Layer constructor.


array([[0.15938702, 0.07735345, 0.32445756, 0.28737563, 0.15173127,
        0.05608574, 0.7042518 , 0.13778047, 0.5521591 , 0.16963945]],
      dtype=float32)

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

tf.nn.softmax(predictions).numpy()
array([[0.08829342, 0.08133952, 0.10414   , 0.10034901, 0.08762004,
        0.07962789, 0.15225099, 0.08640616, 0.13076968, 0.08920329]],
      dtype=float32)

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 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.log(1/10) ~= 2.3.

loss_fn(y_train[:1], predictions).numpy()
2.530391
model.compile(optimizer='adam',
              loss=loss_fn,
              metrics=['accuracy'])

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

model.fit(x_train, y_train, epochs=5)
Train on 60000 samples
Epoch 1/5
60000/60000 [==============================] - 4s 59us/sample - loss: 0.3006 - accuracy: 0.9119
Epoch 2/5
60000/60000 [==============================] - 3s 55us/sample - loss: 0.1435 - accuracy: 0.9569
Epoch 3/5
60000/60000 [==============================] - 3s 56us/sample - loss: 0.1089 - accuracy: 0.9672
Epoch 4/5
60000/60000 [==============================] - 3s 55us/sample - loss: 0.0896 - accuracy: 0.9727
Epoch 5/5
60000/60000 [==============================] - 3s 56us/sample - loss: 0.0768 - accuracy: 0.9762

<tensorflow.python.keras.callbacks.History at 0x7fab01c2c860>

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

model.evaluate(x_test,  y_test, verbose=2)
10000/10000 - 1s - loss: 0.0751 - accuracy: 0.9768

[0.0750549718834227, 0.9768]

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([[7.34887564e-08, 1.00534194e-08, 1.02433842e-05, 1.33675012e-05,
        1.37489839e-10, 7.55593277e-09, 2.09924743e-13, 9.99972105e-01,
        3.26801586e-09, 4.16709372e-06],
       [1.67083755e-07, 5.69196745e-05, 9.99918938e-01, 5.85478028e-06,
        1.07833325e-13, 1.78211703e-05, 2.07623323e-08, 5.33433269e-13,
        2.56460453e-07, 1.63748938e-13],
       [8.32020461e-08, 9.99548495e-01, 2.69682896e-05, 7.11900429e-06,
        4.72620814e-05, 6.43537078e-07, 1.20763198e-05, 3.04942572e-04,
        5.18961606e-05, 3.74096032e-07],
       [9.99958158e-01, 1.45994276e-11, 1.27791664e-05, 9.08889675e-09,
        3.87862798e-07, 4.75454272e-07, 4.18492118e-06, 1.86530760e-05,
        6.06659833e-10, 5.30568195e-06],
       [9.19121874e-07, 4.01698141e-09, 4.01083207e-06, 7.28383753e-09,
        9.97380793e-01, 2.67503566e-08, 7.21894685e-06, 2.47149346e-05,
        2.95606412e-07, 2.58191652e-03]], dtype=float32)>