TF 2.0 is out! Get hands-on practice at TF World, Oct 28-31. Use code TF20 for 20% off select passes. Register now

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 the TensorFlow 2 package. Import TensorFlow into your program:

from __future__ import absolute_import, division, print_function, unicode_literals

# Install TensorFlow

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, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

Train and evaluate the model:

model.fit(x_train, y_train, epochs=5)

model.evaluate(x_test,  y_test, verbose=2)
Train on 60000 samples
Epoch 1/5
60000/60000 [==============================] - 5s 89us/sample - loss: 0.2990 - accuracy: 0.9134
Epoch 2/5
60000/60000 [==============================] - 4s 66us/sample - loss: 0.1419 - accuracy: 0.9582
Epoch 3/5
60000/60000 [==============================] - 4s 66us/sample - loss: 0.1074 - accuracy: 0.9677
Epoch 4/5
60000/60000 [==============================] - 4s 67us/sample - loss: 0.0883 - accuracy: 0.9729
Epoch 5/5
60000/60000 [==============================] - 4s 67us/sample - loss: 0.0746 - accuracy: 0.9771
10000/1 - 1s - loss: 0.0392 - accuracy: 0.9781

[0.07525769539596514, 0.9781]

The image classifier is now trained to ~98% accuracy on this dataset. To learn more, read the TensorFlow tutorials.