![]() |
![]() |
![]() |
![]() |
This short introduction uses Keras to:
- Build a neural network that classifies images.
- Train this neural network.
- And, finally, evaluate the accuracy of the model.
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.
- In Colab, connect to a Python runtime: At the top-right of the menu bar, select CONNECT.
- Run all the notebook code cells: Select Runtime > Run all.
Download and install TensorFlow 2. Import TensorFlow into your program:
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)
])
For each example the model returns a vector of "logits" or "log-odds" scores, one for each class.
predictions = model(x_train[:1]).numpy()
predictions
array([[ 0.67086774, -0.25231966, 0.01695401, -0.20872438, -0.5840499 , 0.20415965, -0.07967779, 0.01230302, 0.2564202 , 0.19890268]], dtype=float32)
The tf.nn.softmax
function converts these logits to "probabilities" for each class:
tf.nn.softmax(predictions).numpy()
array([[0.18120685, 0.07198457, 0.09422877, 0.07519217, 0.05166196, 0.11362814, 0.08554938, 0.09379152, 0.11972431, 0.11303235]], dtype=float32)
The losses.SparseCategoricalCrossentropy
loss takes a vector of logits and a True
index 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: It 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
.
loss_fn(y_train[:1], predictions).numpy()
2.1748242
model.compile(optimizer='adam',
loss=loss_fn,
metrics=['accuracy'])
The Model.fit
method adjusts the model parameters to minimize the loss:
model.fit(x_train, y_train, epochs=5)
Epoch 1/5 1875/1875 [==============================] - 3s 2ms/step - loss: 0.4813 - accuracy: 0.8565 Epoch 2/5 1875/1875 [==============================] - 3s 2ms/step - loss: 0.1533 - accuracy: 0.9553 Epoch 3/5 1875/1875 [==============================] - 3s 2ms/step - loss: 0.1057 - accuracy: 0.9686 Epoch 4/5 1875/1875 [==============================] - 3s 2ms/step - loss: 0.0908 - accuracy: 0.9721 Epoch 5/5 1875/1875 [==============================] - 3s 2ms/step - loss: 0.0700 - accuracy: 0.9788 <tensorflow.python.keras.callbacks.History at 0x7f7c15df5358>
The Model.evaluate
method checks the models performance, usually on a "Validation-set" or "Test-set".
model.evaluate(x_test, y_test, verbose=2)
313/313 - 0s - loss: 0.0748 - accuracy: 0.9758 [0.07476752996444702, 0.9757999777793884]
The image classifier is now trained to ~98% accuracy on this dataset. To learn more, read the TensorFlow tutorials.
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([
model,
tf.keras.layers.Softmax()
])
probability_model(x_test[:5])
<tf.Tensor: shape=(5, 10), dtype=float32, numpy= array([[7.78855878e-08, 6.61358468e-11, 6.59998250e-07, 1.59961201e-05, 2.46321262e-11, 1.29930243e-07, 2.94833365e-14, 9.99982715e-01, 4.22193658e-08, 4.47160573e-07], [4.33228813e-08, 1.27517624e-05, 9.99970555e-01, 1.60829786e-05, 2.47642311e-16, 7.49611928e-09, 1.37607294e-08, 4.11349470e-12, 6.27970280e-07, 9.24811917e-14], [2.03916397e-06, 9.99185383e-01, 1.84247561e-04, 1.05477593e-05, 2.75765397e-05, 5.58228692e-07, 1.01305332e-05, 4.32787347e-04, 1.45807702e-04, 8.87280294e-07], [9.99742925e-01, 5.94857603e-08, 8.63709865e-05, 1.54006088e-08, 1.39324254e-06, 4.43872267e-07, 1.60094583e-04, 5.25048790e-07, 8.63345750e-09, 8.21989215e-06], [5.87329941e-06, 3.34152190e-07, 3.92818802e-05, 3.36201609e-08, 9.96013522e-01, 5.50971926e-08, 4.14997248e-06, 1.14215931e-04, 2.20527431e-06, 3.82039533e-03]], dtype=float32)>