text
stringlengths
0
4.99k
distribution_strategy=None
)
Custom Docker images
By default, TensorFlow Cloud uses a Docker base image supplied by Google and corresponding to your current TensorFlow version. However, you can also specify a custom Docker image to fit your build requirements, if necessary. For this example, we will specify the Docker image from an older version of TensorFlow:
tfc.run(
docker_image_bucket_name=gcp_bucket,
base_docker_image="tensorflow/tensorflow:2.1.0-gpu"
)
Additional metrics
You may find it useful to tag your Cloud jobs with specific labels, or to stream your model's logs during Cloud training. It's good practice to maintain proper labeling on all Cloud jobs, for record-keeping. For this purpose, run() accepts a dictionary of labels up to 64 key-value pairs, which are visible from the Cloud build logs. Logs such as epoch performance and model saving internals can be accessed using the link provided by executing tfc.run or printed to your local terminal using the stream_logs flag.
job_labels = {"job": "mnist-example", "team": "keras-io", "user": "jonah"}
tfc.run(
docker_image_bucket_name=gcp_bucket,
job_labels=job_labels,
stream_logs=True
)
Putting it all together
For an in-depth Colab which uses many of the features described in this guide, follow along this example to train a state-of-the-art model to recognize dog breeds from photos using feature extraction.Training & evaluation with the built-in methods
Author: fchollet
Date created: 2019/03/01
Last modified: 2020/04/13
Description: Complete guide to training & evaluation with fit() and evaluate().
View in Colab • GitHub source
Setup
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
Introduction
This guide covers training, evaluation, and prediction (inference) models when using built-in APIs for training & validation (such as Model.fit(), Model.evaluate() and Model.predict()).
If you are interested in leveraging fit() while specifying your own training step function, see the Customizing what happens in fit() guide.
If you are interested in writing your own training & evaluation loops from scratch, see the guide "writing a training loop from scratch".
In general, whether you are using built-in loops or writing your own, model training & evaluation works strictly in the same way across every kind of Keras model -- Sequential models, models built with the Functional API, and models written from scratch via model subclassing.
This guide doesn't cover distributed training, which is covered in our guide to multi-GPU & distributed training.
API overview: a first end-to-end example
When passing data to the built-in training loops of a model, you should either use NumPy arrays (if your data is small and fits in memory) or tf.data Dataset objects. In the next few paragraphs, we'll use the MNIST dataset as NumPy arrays, in order to demonstrate how to use optimizers, losses, and metrics.
Let's consider the following model (here, we build in with the Functional API, but it could be a Sequential model or a subclassed model as well):
inputs = keras.Input(shape=(784,), name="digits")
x = layers.Dense(64, activation="relu", name="dense_1")(inputs)
x = layers.Dense(64, activation="relu", name="dense_2")(x)
outputs = layers.Dense(10, activation="softmax", name="predictions")(x)
model = keras.Model(inputs=inputs, outputs=outputs)
Here's what the typical end-to-end workflow looks like, consisting of:
Training
Validation on a holdout set generated from the original training data
Evaluation on the test data
We'll use MNIST data for this example.
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# Preprocess the data (these are NumPy arrays)
x_train = x_train.reshape(60000, 784).astype("float32") / 255
x_test = x_test.reshape(10000, 784).astype("float32") / 255
y_train = y_train.astype("float32")
y_test = y_test.astype("float32")
# Reserve 10,000 samples for validation
x_val = x_train[-10000:]
y_val = y_train[-10000:]
x_train = x_train[:-10000]
y_train = y_train[:-10000]
We specify the training configuration (optimizer, loss, metrics):
model.compile(
optimizer=keras.optimizers.RMSprop(), # Optimizer
# Loss function to minimize
loss=keras.losses.SparseCategoricalCrossentropy(),
# List of metrics to monitor
metrics=[keras.metrics.SparseCategoricalAccuracy()],
)
We call fit(), which will train the model by slicing the data into "batches" of size batch_size, and repeatedly iterating over the entire dataset for a given number of epochs.
print("Fit model on training data")
history = model.fit(
x_train,
y_train,
batch_size=64,
epochs=2,
# We pass some validation for
# monitoring validation loss and metrics
# at the end of each epoch
validation_data=(x_val, y_val),
)
Fit model on training data
Epoch 1/2
782/782 [==============================] - 2s 2ms/step - loss: 0.5776 - sparse_categorical_accuracy: 0.8435 - val_loss: 0.1810 - val_sparse_categorical_accuracy: 0.9475