{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "save_and_restore_models.ipynb",
      "version": "0.3.2",
      "views": {},
      "default_view": {},
      "provenance": [],
      "private_outputs": true,
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "metadata": {
        "id": "g_nWetWWd_ns",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "##### Copyright 2018 The TensorFlow Authors."
      ]
    },
    {
      "metadata": {
        "id": "2pHVBk_seED1",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "cellView": "form"
      },
      "cell_type": "code",
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "N_fMsQ-N8I7j",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "cellView": "form"
      },
      "cell_type": "code",
      "source": [
        "#@title MIT License\n",
        "#\n",
        "# Copyright (c) 2017 François Chollet\n",
        "#\n",
        "# Permission is hereby granted, free of charge, to any person obtaining a\n",
        "# copy of this software and associated documentation files (the \"Software\"),\n",
        "# to deal in the Software without restriction, including without limitation\n",
        "# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n",
        "# and/or sell copies of the Software, and to permit persons to whom the\n",
        "# Software is furnished to do so, subject to the following conditions:\n",
        "#\n",
        "# The above copyright notice and this permission notice shall be included in\n",
        "# all copies or substantial portions of the Software.\n",
        "#\n",
        "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n",
        "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n",
        "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n",
        "# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n",
        "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n",
        "# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n",
        "# DEALINGS IN THE SOFTWARE."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "pZJ3uY9O17VN",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "# Save and restore models"
      ]
    },
    {
      "metadata": {
        "id": "M4Ata7_wMul1",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/keras/save_and_restore_models\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/models/blob/master/samples/core/tutorials/keras/save_and_restore_models.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/models/blob/master/samples/core/tutorials/keras/save_and_restore_models.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "metadata": {
        "id": "mBdde4YJeJKF",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "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 practitioners 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/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/guide/saved_model) guide or [Saving in eager](https://www.tensorflow.org/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": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "!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:"
      ]
    },
    {
      "metadata": {
        "id": "7Nm7Tyb-gRt-",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "from __future__ import absolute_import, division, print_function\n",
        "\n",
        "import os\n",
        "\n",
        "import tensorflow as tf\n",
        "from tensorflow import keras\n",
        "\n",
        "tf.__version__"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "9rGfFwE9XVwz",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()\n",
        "\n",
        "train_labels = train_labels[:1000]\n",
        "test_labels = test_labels[:1000]\n",
        "\n",
        "train_images = train_images[:1000].reshape(-1, 28 * 28) / 255.0\n",
        "test_images = test_images[:1000].reshape(-1, 28 * 28) / 255.0"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "anG3iVoXyZGI",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Define a model"
      ]
    },
    {
      "metadata": {
        "id": "wynsOBfby0Pa",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Let's build a simple model we'll use to demonstrate saving and loading weights."
      ]
    },
    {
      "metadata": {
        "id": "0HZbJIjxyX1S",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "# Returns a short sequential model\n",
        "def create_model():\n",
        "  model = tf.keras.models.Sequential([\n",
        "    keras.layers.Dense(512, activation=tf.nn.relu, input_shape=(784,)),\n",
        "    keras.layers.Dropout(0.2),\n",
        "    keras.layers.Dense(10, activation=tf.nn.softmax)\n",
        "  ])\n",
        "  \n",
        "  model.compile(optimizer=tf.keras.optimizers.Adam(), \n",
        "                loss=tf.keras.losses.sparse_categorical_crossentropy,\n",
        "                metrics=['accuracy'])\n",
        "  \n",
        "  return model\n",
        "\n",
        "\n",
        "# Create a basic model instance\n",
        "model = create_model()\n",
        "model.summary()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "soDE0W_KH8rG",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Save checkpoints during training"
      ]
    },
    {
      "metadata": {
        "id": "mRyd5qQQIXZm",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "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:"
      ]
    },
    {
      "metadata": {
        "id": "IFPuhwntH8VH",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "checkpoint_path = \"training_1/cp.ckpt\"\n",
        "checkpoint_dir = os.path.dirname(checkpoint_path)\n",
        "\n",
        "# Create checkpoint callback\n",
        "cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, \n",
        "                                                 save_weights_only=True,\n",
        "                                                 verbose=1)\n",
        "\n",
        "model = create_model()\n",
        "\n",
        "model.fit(train_images, train_labels,  epochs = 10, \n",
        "          validation_data = (test_images,test_labels),\n",
        "          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": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "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):"
      ]
    },
    {
      "metadata": {
        "id": "Fp5gbuiaPqCT",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "model = create_model()\n",
        "\n",
        "loss, acc = model.evaluate(test_images, test_labels)\n",
        "print(\"Untrained model, accuracy: {:5.2f}%\".format(100*acc))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "1DTKpZssRSo3",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Then load the weights from the checkpoint, and re-evaluate:"
      ]
    },
    {
      "metadata": {
        "id": "2IZxbwiRRSD2",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "model.load_weights(checkpoint_path)\n",
        "loss,acc = model.evaluate(test_images, test_labels)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "bpAbKkAyVPV8",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Checkpoint callback options\n",
        "\n",
        "The callback provides several options to give the resulting checkpoints unique names, and adjust the checkpointing frequency.\n",
        "\n",
        "Train a new model, and save uniquely named checkpoints once every 5-epochs:\n"
      ]
    },
    {
      "metadata": {
        "id": "mQF_dlgIVOvq",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "# include the epoch in the file name. (uses `str.format`)\n",
        "checkpoint_path = \"training_2/cp-{epoch:04d}.ckpt\"\n",
        "checkpoint_dir = os.path.dirname(checkpoint_path)\n",
        "\n",
        "cp_callback = tf.keras.callbacks.ModelCheckpoint(\n",
        "    checkpoint_path, verbose=1, save_weights_only=True,\n",
        "    # Save weights, every 5-epochs.\n",
        "    period=5)\n",
        "\n",
        "model = create_model()\n",
        "model.fit(train_images, train_labels,\n",
        "          epochs = 50, callbacks = [cp_callback],\n",
        "          validation_data = (test_images,test_labels),\n",
        "          verbose=0)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "1zFrKTjjavWI",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Now, have a look at the resulting checkpoints (sorting by modification date):"
      ]
    },
    {
      "metadata": {
        "id": "1AN_fnuyR41H",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "import pathlib\n",
        "\n",
        "# Sort the checkpoints by modification time.\n",
        "checkpoints = pathlib.Path(checkpoint_dir).glob(\"*.index\")\n",
        "checkpoints = sorted(checkpoints, key=lambda cp:cp.stat().st_mtime)\n",
        "checkpoints = [cp.with_suffix('') for cp in checkpoints]\n",
        "latest = str(checkpoints[-1])\n",
        "checkpoints"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "Zk2ciGbKg561",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Note: the default tensorflow format only saves the 5 most recent checkpoints.\n",
        "\n",
        "To test, reset the model and load the latest checkpoint:"
      ]
    },
    {
      "metadata": {
        "id": "3M04jyK-H3QK",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "model = create_model()\n",
        "model.load_weights(latest)\n",
        "loss, acc = model.evaluate(test_images, test_labels)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "c2OxsJOTHxia",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## What are these files?"
      ]
    },
    {
      "metadata": {
        "id": "JtdYhvWnH2ib",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "The above code stores the weights to a collection of [checkpoint](https://www.tensorflow.org/guide/saved_model#save_and_restore_variables)-formatted files that contain only the trained weights in a binary format. Checkpoints contain:\n",
        "\n",
        "* One or more shards that contain your model's weights. \n",
        "* An index file that indicates which weights are stored in 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": [
        "## Manually 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."
      ]
    },
    {
      "metadata": {
        "id": "R7W5plyZ-u9X",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "# Save the weights\n",
        "model.save_weights('./checkpoints/my_checkpoint')\n",
        "\n",
        "# Restore the weights\n",
        "model = create_model()\n",
        "model.load_weights('./checkpoints/my_checkpoint')\n",
        "\n",
        "loss,acc = model.evaluate(test_images, test_labels)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "kOGlxPRBEvV1",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Save the entire model\n",
        "\n",
        "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"
      ]
    },
    {
      "metadata": {
        "id": "m2dkmJVCGUia",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "model = create_model()\n",
        "\n",
        "model.fit(train_images, train_labels, epochs=5)\n",
        "\n",
        "# Save entire model to a HDF5 file\n",
        "model.save('my_model.h5')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "GWmttMOqS68S",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Now recreate the model from that file:"
      ]
    },
    {
      "metadata": {
        "id": "5NDMO_7kS6Do",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "# Recreate the exact same model, including weights and optimizer.\n",
        "new_model = keras.models.load_model('my_model.h5')\n",
        "new_model.summary()\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "JXQpbTicTBwt",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Check its accuracy:"
      ]
    },
    {
      "metadata": {
        "id": "jwEaj9DnTCVA",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "cell_type": "code",
      "source": [
        "loss, acc = new_model.evaluate(test_images, test_labels)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "dGXqd4wWJl8O",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "This technique saves everything:\n",
        "\n",
        "* The weight values\n",
        "* The model's configuration(architecture)\n",
        "* The optimizer configuration\n",
        "\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 lose 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/guide/keras) shows more about saving and loading models with `tf.keras`.\n",
        "\n",
        "* See [Saving in eager](https://www.tensorflow.org/guide/eager#object_based_saving) for saving during eager execution.\n",
        "\n",
        "* The [Save and Restore](https://www.tensorflow.org/guide/saved_model) guide has low-level details about TensorFlow saving."
      ]
    }
  ]
}
