Comment on page
Introduction to Tensorflow
Copyright 2019 The TensorFlow Authors
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
- 1.Load a prebuilt dataset.
- 2.Build a neural network machine learning model that classifies images.
- 3.Train this neural network.
- 4.Evaluate the accuracy of the model.
This tutorial is a Google Colaboratory notebook. 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.
import tensorflow as tf
print("TensorFlow version:", tf.__version__)
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
model = tf.keras.models.Sequential([
predictions = model(x_train[:1]).numpy()
tf.nn.softmaxfunction converts these logits to probabilities for each class:
Note: It is possible to bake the
tf.nn.softmaxfunction into the activation function for the last layer of the network. While this can make the model output more directly interpretable, this approach is discouraged as it's impossible to provide an exact and numerically stable loss calculation for all models when using a softmax output.
Define a loss function for training using
losses.SparseCategoricalCrossentropy, which takes a vector of logits and a
Trueindex and returns a scalar loss for each example.
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
This loss is equal to the negative log probability of the true class: The loss is zero if the model is sure of the correct class.
This untrained model gives probabilities close to random (1/10 for each class), so the initial loss should be close to
-tf.math.log(1/10) ~= 2.3.
Before you start training, configure and compile the model using Keras
Model.compile. Set the
adam, set the
loss_fnfunction you defined earlier, and specify a metric to be evaluated for the model by setting the
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test, verbose=2)
If you want your model to return a probability, you can wrap the trained model, and attach the softmax to it:
probability_model = tf.keras.Sequential([