" <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a> \n",
"</td><td>\n",
"<a target=\"_blank\" href=\"https://github.com/tensorflow/models/blob/master/samples/core/get_started/save_and_restore_models.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on Github</a></td></table>\n"
]
},
{
"metadata": {
"id": "mBdde4YJeJKF",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"\n",
"\n",
"Model progress can be saved during—and after—training. This means a model can resume where it left off and avoid long training times. Saving also means you can share your model and others can recreate your work. When publishing research models and techniques, most machine learning practioners share:\n",
"\n",
"* code to create the model, and\n",
"* the trained weights, or parameters, for the model\n",
"\n",
"Sharing this data helps others understand how the model works and try it themselves with new data.\n",
"\n",
"Caution: Be careful with untrusted code—TensorFlow models are code. See [Using TensorFlow Securely](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md) for details.\n",
"\n",
"### Options\n",
"\n",
"There are different ways to save TensorFlow models—depending on the API you're using. This guide uses [tf.keras](https://www.tensorflow.org/programmers_guide/keras), a high-level API to build and train models in TensorFlow. For other approaches, see the TensorFlow [Save and Restore](https://www.tensorflow.org/programmers_guide/saved_model) guide or [Saving in eager](https://www.tensorflow.org/programmers_guide/eager#object_based_saving).\n"
]
},
{
"metadata": {
"id": "xCUREq7WXgvg",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Setup\n",
"\n",
"### Installs and imports"
]
},
{
"metadata": {
"id": "7l0MiTOrXtNv",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Install and import TensorFlow and dependencies:"
]
},
{
"metadata": {
"id": "RzIOVSdnMYyO",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"!pip install --pre --upgrade tensorflow\n",
"!pip install h5py pyyaml "
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "SbGsznErXWt6",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Get an example dataset\n",
"\n",
"We'll use the [MNIST dataset](http://yann.lecun.com/exdb/mnist/) to train our model to demonstrate saving weights. To speed up these demonstration runs, only use the first 1000 examples:"
"The primary use case is to automatically save checkpoints *during* and at *the end* of training. This way you can use a trained model without having to retrain it, or pick-up training where you left of—in case the training process was interrupted.\n",
"\n",
"`tf.keras.callbacks.ModelCheckpoint` is a callback that performs this task. The callback takes a couple of arguments to configure checkpointing.\n",
"\n",
"### Checkpoint callback usage\n",
"\n",
"Train the model and pass it the `ModelCheckpoint` callback:"
" callbacks = [cp_callback]) # pass callback to training"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "rlM-sgyJO084",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"This creates a single collection of TensorFlow checkpoint files that are updated at the end of each epoch:"
]
},
{
"metadata": {
"id": "gXG5FVKFOVQ3",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"!ls {checkpoint_dir}"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "wlRN_f56Pqa9",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Create a new, untrained model. When restoring a model from only weights, you must have a model with the same architecture as the original model. Since it's the same model architecture, we can share weights despite that it's a different *instance* of the model.\n",
"\n",
"Now rebuild a fresh, untrained model, and evaluate it on the test set. An untrained model will perform at chance levels (~10% accuracy):"
"The above code stores the weights to a collection of [checkpoint](https://www.tensorflow.org/programmers_guide/saved_model#save_and_restore_variables)-formatted files that contains only the trained weights in a binary format. Checkpoints contain:\n",
"* One or more shards that contain your model's weights. \n",
"* An index file that indicates which weights are stored in a which shard. \n",
"\n",
"If you are only training a model on a single machine, you'll have one shard with the suffix: `.data-00000-of-00001`"
]
},
{
"metadata": {
"id": "S_FA-ZvxuXQV",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Manualy save weights\n",
"\n",
"Above you saw how to load the weights into a model.\n",
"\n",
"Manually saving the weights is just as simple, use the `Model.save_weights` method."
"The entire model can be saved to a file that contains the weight values, the model's configuration, and even the optimizer's configuration. This allows you to checkpoint a model and resume training later—from the exact same state—without access to the original code.\n",
"\n",
"Saving a fully-functional model in Keras is very useful—you can load them in [TensorFlow.js](https://js.tensorflow.org/tutorials/import-keras.html) and then train and run them in web browsers.\n",
"\n",
"Keras provides a basic save format using the [HDF5](https://en.wikipedia.org/wiki/Hierarchical_Data_Format) standard. For our purposes, the saved model can be treated as a single binary blob.\n"
"Keras saves models by inspecting the architecture. Currently, it is not able to save TensorFlow optimizers (from `tf.train`). When using those you will need to re-compile the model after loading, and you will loose the state of the optimizer.\n"
]
},
{
"metadata": {
"id": "eUYTzSz5VxL2",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## What's Next\n",
"\n",
"That was a quick guide to saving and loading in with `tf.keras`.\n",
"\n",
"* The [tf.keras guide](https://www.tensorflow.org/programmers_guide/keras) shows more about saving and loading models with `tf.keras`.\n",
"\n",
"* See [Saving in eager](https://www.tensorflow.org/programmers_guide/eager#object_based_saving) for saving during eager execution.\n",
"\n",
"* The [Save and Restore](https://www.tensorflow.org/programmers_guide/saved_model) guide has low-level details about TensorFlow saving."