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 follow this tutorial, run the notebook in Google Colab by clicking the button at the top of this page.

  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, unicode_literals

!pip install -q tensorflow-gpu==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)
WARNING: Logging before flag parsing goes to stderr.
W0520 19:08:57.525783 140474128131840 deprecation.py:323] From /home/kbuilder/.local/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

Epoch 1/5
60000/60000 [==============================] - 4s 62us/sample - loss: 0.2949 - accuracy: 0.9146
Epoch 2/5
60000/60000 [==============================] - 4s 59us/sample - loss: 0.1449 - accuracy: 0.9569
Epoch 3/5
60000/60000 [==============================] - 3s 56us/sample - loss: 0.1092 - accuracy: 0.9670
Epoch 4/5
60000/60000 [==============================] - 4s 59us/sample - loss: 0.0899 - accuracy: 0.9724
Epoch 5/5
60000/60000 [==============================] - 4s 59us/sample - loss: 0.0762 - accuracy: 0.9760
10000/10000 [==============================] - 0s 36us/sample - loss: 0.0833 - accuracy: 0.9737

[0.08330829613315872, 0.9737]

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