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

from __future__ import absolute_import, division, print_function, unicode_literals

# Install TensorFlow
!pip install -q tensorflow==2.0.0-beta1

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.
W0614 17:57:49.842484 140243051292416 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 [==============================] - 4s 71us/sample - loss: 0.2957 - accuracy: 0.9141
Epoch 2/5
60000/60000 [==============================] - 4s 66us/sample - loss: 0.1408 - accuracy: 0.9589
Epoch 3/5
60000/60000 [==============================] - 4s 66us/sample - loss: 0.1059 - accuracy: 0.9676
Epoch 4/5
60000/60000 [==============================] - 4s 66us/sample - loss: 0.0875 - accuracy: 0.9727
Epoch 5/5
60000/60000 [==============================] - 4s 66us/sample - loss: 0.0744 - accuracy: 0.9768
10000/10000 [==============================] - 0s 40us/sample - loss: 0.0782 - accuracy: 0.9762

[0.0781548868638929, 0.9762]

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