Watch talks from the 2019 TensorFlow Dev Summit Watch now

Get started with TensorFlow 2.0 for beginners

View on TensorFlow.org Run in Google Colab View source on GitHub

This is a Google Colaboratory notebook file. Python programs are run directly in the browser—a great way to learn and use TensorFlow. To run the Colab notebook:

  1. 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.

For more examples and guides, see the TensorFlow tutorials.

To get started, import the TensorFlow library into your program:

from __future__ import absolute_import, division, print_function

!pip install -q tensorflow==2.0.0-alpha0
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
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11493376/11490434 [==============================] - 0s 0us/step

Build the tf.keras.Sequential model by stacking layers. Choose an optimizer and loss function used 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 model:

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

model.evaluate(x_test, y_test)
Epoch 1/5
60000/60000 [==============================] - 5s 91us/sample - loss: 0.2999 - accuracy: 0.9124
Epoch 2/5
60000/60000 [==============================] - 5s 89us/sample - loss: 0.1416 - accuracy: 0.9582
Epoch 3/5
60000/60000 [==============================] - 5s 88us/sample - loss: 0.1082 - accuracy: 0.9665
Epoch 4/5
60000/60000 [==============================] - 5s 82us/sample - loss: 0.0873 - accuracy: 0.9738
Epoch 5/5
60000/60000 [==============================] - 5s 86us/sample - loss: 0.0758 - accuracy: 0.9757
10000/10000 [==============================] - 0s 42us/sample - loss: 0.0703 - accuracy: 0.9777

[0.07026492959200405, 0.9777]

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