Join us at TensorFlow World, Oct 28-31. Use code TF20 for 20% off select passes. Register now

Get started with TensorFlow 2.0 for beginners

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

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

from __future__ import absolute_import, division, print_function, unicode_literals

# Install TensorFlow
try:
  # %tensorflow_version only exists in Colab.
  %tensorflow_version 2.x
except Exception:
  pass

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)
WARNING: Logging before flag parsing goes to stderr.
W0813 06:09:22.838786 140200058390272 deprecation.py:323] From /tmpfs/src/tf_docs_env/lib/python3.5/site-packages/tensorflow/python/ops/math_grad.py:1250: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where

Train on 60000 samples
Epoch 1/5
60000/60000 [==============================] - 7s 110us/sample - loss: 0.2972 - accuracy: 0.9130
Epoch 2/5
60000/60000 [==============================] - 6s 104us/sample - loss: 0.1475 - accuracy: 0.9561
Epoch 3/5
60000/60000 [==============================] - 6s 107us/sample - loss: 0.1087 - accuracy: 0.9666
Epoch 4/5
60000/60000 [==============================] - 6s 108us/sample - loss: 0.0885 - accuracy: 0.9728
Epoch 5/5
60000/60000 [==============================] - 7s 110us/sample - loss: 0.0766 - accuracy: 0.9766
10000/10000 [==============================] - 1s 72us/sample - loss: 0.0731 - accuracy: 0.9786

[0.07306053459341638, 0.9786]

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