<commit_before>{
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "save_and_load.ipynb",
      "private_outputs": true,
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0,
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "g_nWetWWd_ns"
      },
      "source": [
        "##### Copyright 2019 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "form",
        "colab": {},
        "colab_type": "code",
        "id": "2pHVBk_seED1"
      },
      "outputs": [],
      "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."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "form",
        "colab": {},
        "colab_type": "code",
        "id": "N_fMsQ-N8I7j"
      },
      "outputs": [],
      "source": [
        "#@title MIT License\n",
        "#\n",
        "# Copyright (c) 2017 <NAME>\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."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "pZJ3uY9O17VN"
      },
      "source": [
        "# Save and load models"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "M4Ata7_wMul1"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/keras/save_and_load\"><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/docs/blob/master/site/en/tutorials/keras/save_and_load.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/docs/blob/master/site/en/tutorials/keras/save_and_load.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/keras/save_and_load.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "mBdde4YJeJKF"
      },
      "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)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "xCUREq7WXgvg"
      },
      "source": [
        "## Setup\n",
        "\n",
        "### Installs and imports"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "7l0MiTOrXtNv"
      },
      "source": [
        "Install and import TensorFlow and dependencies:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "RzIOVSdnMYyO"
      },
      "outputs": [],
      "source": [
        "try:\n",
        "  # %tensorflow_version only exists in Colab.\n",
        "  %tensorflow_version 2.x\n",
        "except Exception:\n",
        "  pass\n",
        "\n",
        "!pip install pyyaml h5py  # Required to save models in HDF5 format"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "7Nm7Tyb-gRt-"
      },
      "outputs": [],
      "source": [
        "from __future__ import absolute_import, division, print_function, unicode_literals\n",
        "\n",
        "import os\n",
        "\n",
        "import tensorflow as tf\n",
        "from tensorflow import keras\n",
        "\n",
        "print(tf.version.VERSION)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "SbGsznErXWt6"
      },
      "source": [
        "### Get an example dataset\n",
        "\n",
        "To demonstrate how to save and load weights, you'll use the [MNIST dataset](http://yann.lecun.com/exdb/mnist/). To speed up these runs, use the first 1000 examples:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "9rGfFwE9XVwz"
      },
      "outputs": [],
      "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"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "anG3iVoXyZGI"
      },
      "source": [
        "### Define a model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "wynsOBfby0Pa"
      },
      "source": [
        "Start by building a simple sequential model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "0HZbJIjxyX1S"
      },
      "outputs": [],
      "source": [
        "# Define a simple sequential model\n",
        "def create_model():\n",
        "  model = tf.keras.models.Sequential([\n",
        "    keras.layers.Dense(512, activation='relu', input_shape=(784,)),\n",
        "    keras.layers.Dropout(0.2),\n",
        "    keras.layers.Dense(10)\n",
        "  ])\n",
        "\n",
        "  model.compile(optimizer='adam',\n",
        "                loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "                metrics=['accuracy'])\n",
        "\n",
        "  return model\n",
        "\n",
        "# Create a basic model instance\n",
        "model = create_model()\n",
        "\n",
        "# Display the model's architecture\n",
        "model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "soDE0W_KH8rG"
      },
      "source": [
        "## Save checkpoints during training"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "mRyd5qQQIXZm"
      },
      "source": [
        "You can use a trained model without having to retrain it, or pick-up training where you left off—in case the training process was interrupted. The `tf.keras.callbacks.ModelCheckpoint` callback allows to continually save the model both *during* and at *the end* of training.\n",
        "\n",
        "### Checkpoint callback usage\n",
        "\n",
        "Create a `tf.keras.callbacks.ModelCheckpoint` callback that saves weights only during training:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "IFPuhwntH8VH"
      },
      "outputs": [],
      "source": [
        "checkpoint_path = \"training_1/cp.ckpt\"\n",
        "checkpoint_dir = os.path.dirname(checkpoint_path)\n",
        "\n",
        "# Create a callback that saves the model's weights\n",
        "cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,\n",
        "                                                 save_weights_only=True,\n",
        "                                                 verbose=1)\n",
        "\n",
        "# Train the model with the new callback\n",
        "model.fit(train_images, \n",
        "          train_labels,  \n",
        "          epochs=10,\n",
        "          validation_data=(test_images,test_labels),\n",
        "          callbacks=[cp_callback])  # Pass callback to training\n",
        "\n",
        "# This may generate warnings related to saving the state of the optimizer.\n",
        "# These warnings (and similar warnings throughout this notebook)\n",
        "# are in place to discourage outdated usage, and can be ignored."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "rlM-sgyJO084"
      },
      "source": [
        "This creates a single collection of TensorFlow checkpoint files that are updated at the end of each epoch:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "gXG5FVKFOVQ3"
      },
      "outputs": [],
      "source": [
        "!ls {checkpoint_dir}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "wlRN_f56Pqa9"
      },
      "source": [
        "Create a new, untrained model. When restoring a model from weights-only, you must have a model with the same architecture as the original model. Since it's the same model architecture, you 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):"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "Fp5gbuiaPqCT"
      },
      "outputs": [],
      "source": [
        "# Create a basic model instance\n",
        "model = create_model()\n",
        "\n",
        "# Evaluate the model\n",
        "loss, acc = model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Untrained model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "1DTKpZssRSo3"
      },
      "source": [
        "Then load the weights from the checkpoint and re-evaluate:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "2IZxbwiRRSD2"
      },
      "outputs": [],
      "source": [
        "# Loads the weights\n",
        "model.load_weights(checkpoint_path)\n",
        "\n",
        "# Re-evaluate the model\n",
        "loss,acc = model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "bpAbKkAyVPV8"
      },
      "source": [
        "### Checkpoint callback options\n",
        "\n",
        "The callback provides several options to provide unique names for checkpoints and adjust the checkpointing frequency.\n",
        "\n",
        "Train a new model, and save uniquely named checkpoints once every five epochs:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "mQF_dlgIVOvq"
      },
      "outputs": [],
      "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",
        "# Create a callback that saves the model's weights every 5 epochs\n",
        "cp_callback = tf.keras.callbacks.ModelCheckpoint(\n",
        "    filepath=checkpoint_path, \n",
        "    verbose=1, \n",
        "    save_weights_only=True,\n",
        "    period=5)\n",
        "\n",
        "# Create a new model instance\n",
        "model = create_model()\n",
        "\n",
        "# Save the weights using the `checkpoint_path` format\n",
        "model.save_weights(checkpoint_path.format(epoch=0))\n",
        "\n",
        "# Train the model with the new callback\n",
        "model.fit(train_images, \n",
        "              train_labels,\n",
        "              epochs=50, \n",
        "              callbacks=[cp_callback],\n",
        "              validation_data=(test_images,test_labels),\n",
        "              verbose=0)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "1zFrKTjjavWI"
      },
      "source": [
        "Now, look at the resulting checkpoints and choose the latest one:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "p64q3-V4sXt0"
      },
      "outputs": [],
      "source": [
        "!ls {checkpoint_dir}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "1AN_fnuyR41H"
      },
      "outputs": [],
      "source": [
        "latest = tf.train.latest_checkpoint(checkpoint_dir)\n",
        "latest"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Zk2ciGbKg561"
      },
      "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:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "3M04jyK-H3QK"
      },
      "outputs": [],
      "source": [
        "# Create a new model instance\n",
        "model = create_model()\n",
        "\n",
        "# Load the previously saved weights\n",
        "model.load_weights(latest)\n",
        "\n",
        "# Re-evaluate the model\n",
        "loss, acc = model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "c2OxsJOTHxia"
      },
      "source": [
        "## What are these files?"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "JtdYhvWnH2ib"
      },
      "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",
        "* 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`"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "S_FA-ZvxuXQV"
      },
      "source": [
        "## Manually save weights\n",
        "\n",
        "You saw how to load the weights into a model. Manually saving them is just as simple with the `Model.save_weights` method. By default, `tf.keras`—and `save_weights` in particular—uses the TensorFlow [checkpoint](../../guide/checkpoint.ipynb) format with a `.ckpt` extension (saving in [HDF5](https://js.tensorflow.org/tutorials/import-keras.html) with a `.h5` extension is covered in the [Save and serialize models](../../guide/keras/save_and_serialize#weights-only_saving_in_savedmodel_format) guide):"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "R7W5plyZ-u9X"
      },
      "outputs": [],
      "source": [
        "# Save the weights\n",
        "model.save_weights('./checkpoints/my_checkpoint')\n",
        "\n",
        "# Create a new model instance\n",
        "model = create_model()\n",
        "\n",
        "# Restore the weights\n",
        "model.load_weights('./checkpoints/my_checkpoint')\n",
        "\n",
        "# Evaluate the model\n",
        "loss,acc = model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "kOGlxPRBEvV1"
      },
      "source": [
        "## Save the entire model\n",
        "\n",
        "Call [`model.save`](https://www.tensorflow.org/api_docs/python/tf/keras/Model#save) to save the a model's architecture, weights, and training configuration in a single file/folder. This allows you to export a model so it can be used without access to the original Python code*. Since the optimizer-state is recovered, you can resume training from exactly where you left off.\n",
        "\n",
        "Saving a fully-functional model is very useful—you can load them in TensorFlow.js ([HDF5](https://js.tensorflow.org/tutorials/import-keras.html), [Saved Model](https://js.tensorflow.org/tutorials/import-saved-model.html)) and then train and run them in web browsers, or convert them to run on mobile devices using TensorFlow Lite ([HDF5](https://www.tensorflow.org/lite/convert/python_api#exporting_a_tfkeras_file_), [Saved Model](https://www.tensorflow.org/lite/convert/python_api#exporting_a_savedmodel_))\n",
        "\n",
        "\\*Custom objects (e.g. subclassed models or layers) require special attention when saving and loading. See the **Saving custom objects** section below "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "SkGwf-50zLNn"
      },
      "source": [
        "### HDF5 format\n",
        "\n",
        "Keras provides a basic save format using the [HDF5](https://en.wikipedia.org/wiki/Hierarchical_Data_Format) standard. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "m2dkmJVCGUia"
      },
      "outputs": [],
      "source": [
        "# Create and train a new model instance.\n",
        "model = create_model()\n",
        "model.fit(train_images, train_labels, epochs=5)\n",
        "\n",
        "# Save the entire model to a HDF5 file.\n",
        "# The '.h5' extension indicates that the model should be saved to HDF5.\n",
        "model.save('my_model.h5') "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "GWmttMOqS68S"
      },
      "source": [
        "Now, recreate the model from that file:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "5NDMO_7kS6Do"
      },
      "outputs": [],
      "source": [
        "# Recreate the exact same model, including its weights and the optimizer\n",
        "new_model = tf.keras.models.load_model('my_model.h5')\n",
        "\n",
        "# Show the model architecture\n",
        "new_model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "JXQpbTicTBwt"
      },
      "source": [
        "Check its accuracy:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "jwEaj9DnTCVA"
      },
      "outputs": [],
      "source": [
        "loss, acc = new_model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print('Restored model, accuracy: {:5.2f}%'.format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "dGXqd4wWJl8O"
      },
      "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"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "kPyhgcoVzqUB"
      },
      "source": [
        "### SavedModel format"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "LtcN4VIb7JkK"
      },
      "source": [
        "The SavedModel format is another way to serialize models. Models saved in this format can be restored using `tf.keras.models.load_model` and are compatible with TensorFlow Serving. The [SavedModel guide](https://www.tensorflow.org/guide/saved_model) goes into detail about how to serve/inspect the SavedModel. The section below illustrates the steps to saving and restoring the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "sI1YvCDFzpl3"
      },
      "outputs": [],
      "source": [
        "# Create and train a new model instance.\n",
        "model = create_model()\n",
        "model.fit(train_images, train_labels, epochs=5)\n",
        "\n",
        "# Save the entire model as a SavedModel.\n",
        "!mkdir -p saved_model\n",
        "model.save('saved_model/my_model') "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "iUvT_3qE8hV5"
      },
      "source": [
        "The SavedModel format is a directory containing a protobuf binary and a Tensorflow checkpoint. Inspect the saved model directory:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "sq8fPglI1RWA"
      },
      "outputs": [],
      "source": [
        "# my_model directory\n",
        "!ls saved_model\n",
        "\n",
        "# Contains an assets folder, saved_model.pb, and variables folder.\n",
        "!ls saved_model/my_model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "B7qfpvpY9HCe"
      },
      "source": [
        "Reload a fresh Keras model from the saved model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "0YofwHdN0pxa"
      },
      "outputs": [],
      "source": [
        "new_model = tf.keras.models.load_model('saved_model/my_model')\n",
        "\n",
        "# Check its architecture\n",
        "new_model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "uWwgNaz19TH2"
      },
      "source": [
        "The restored model is compiled with the same arguments as the original model. Try running evaluate and predict with the loaded model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "Yh5Mu0yOgE5J"
      },
      "outputs": [],
      "source": [
        "# Evaluate the restored model\n",
        "loss, acc = new_model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print('Restored model, accuracy: {:5.2f}%'.format(100*acc))\n",
        "\n",
        "print(new_model.predict(test_images).shape)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "kAUKJQyGqTNH"
      },
      "source": [
        "### Saving custom objects\n",
        "\n",
        "If you are using the SavedModel format, you can skip this section. The key difference between HDF5 and SavedModel is that HDF5 uses object configs to save the model architecture, while SavedModel saves the execution graph. Thus, SavedModels are able to save custom objects like subclassed models and custom layers without requiring the orginal code.\n",
        "\n",
        "To save custom objects to HDF5, you must do the following:\n",
        "\n",
        "1. Define a `get_config` method in your object, and optionally a `from_config` classmethod.\n",
        "  * `get_config(self)` returns a JSON-serializable dictionary of parameters needed to recreate the object.\n",
        "  * `from_config(cls, config)` uses the returned config from `get_config` to create a new object. By default, this function will use the config as initialization kwargs (`return cls(**config)`).\n",
        "2. Pass the object to the `custom_objects` argument when loading the model. The argument must be a dictionary mapping the string class name to the Python class. E.g. `tf.keras.models.load_model(path, custom_objects={'CustomLayer': CustomLayer})`\n",
        "\n",
        "See the [Writing layers and models from scratch](https://www.tensorflow.org/guide/keras/custom_layers_and_models) tutorial for examples of custom objects and `get_config`.\n"
      ]
    }
  ]
}<commit_msg>Updating the save_and_load tutorial.<commit_after>{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "g_nWetWWd_ns"
      },
      "source": [
        "##### Copyright 2019 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "form",
        "colab": {},
        "colab_type": "code",
        "id": "2pHVBk_seED1"
      },
      "outputs": [],
      "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."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "form",
        "colab": {},
        "colab_type": "code",
        "id": "N_fMsQ-N8I7j"
      },
      "outputs": [],
      "source": [
        "#@title MIT License\n",
        "#\n",
        "# Copyright (c) 2017 <NAME>\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."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "pZJ3uY9O17VN"
      },
      "source": [
        "# Save and load models"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "M4Ata7_wMul1"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/keras/save_and_load\"><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/docs/blob/master/site/en/tutorials/keras/save_and_load.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/docs/blob/master/site/en/tutorials/keras/save_and_load.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/keras/save_and_load.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "mBdde4YJeJKF"
      },
      "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)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "xCUREq7WXgvg"
      },
      "source": [
        "## Setup\n",
        "\n",
        "### Installs and imports"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "7l0MiTOrXtNv"
      },
      "source": [
        "Install and import TensorFlow and dependencies:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "RzIOVSdnMYyO"
      },
      "outputs": [],
      "source": [
        "try:\n",
        "  # %tensorflow_version only exists in Colab.\n",
        "  %tensorflow_version 2.x\n",
        "except Exception:\n",
        "  pass\n",
        "\n",
        "!pip install pyyaml h5py  # Required to save models in HDF5 format"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "7Nm7Tyb-gRt-"
      },
      "outputs": [],
      "source": [
        "from __future__ import absolute_import, division, print_function, unicode_literals\n",
        "\n",
        "import os\n",
        "\n",
        "import tensorflow as tf\n",
        "from tensorflow import keras\n",
        "\n",
        "print(tf.version.VERSION)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "SbGsznErXWt6"
      },
      "source": [
        "### Get an example dataset\n",
        "\n",
        "To demonstrate how to save and load weights, you'll use the [MNIST dataset](http://yann.lecun.com/exdb/mnist/). To speed up these runs, use the first 1000 examples:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "9rGfFwE9XVwz"
      },
      "outputs": [],
      "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"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "anG3iVoXyZGI"
      },
      "source": [
        "### Define a model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "wynsOBfby0Pa"
      },
      "source": [
        "Start by building a simple sequential model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "0HZbJIjxyX1S"
      },
      "outputs": [],
      "source": [
        "# Define a simple sequential model\n",
        "def create_model():\n",
        "  model = tf.keras.models.Sequential([\n",
        "    keras.layers.Dense(512, activation='relu', input_shape=(784,)),\n",
        "    keras.layers.Dropout(0.2),\n",
        "    keras.layers.Dense(10)\n",
        "  ])\n",
        "\n",
        "  model.compile(optimizer='adam',\n",
        "                loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "                metrics=['accuracy'])\n",
        "\n",
        "  return model\n",
        "\n",
        "# Create a basic model instance\n",
        "model = create_model()\n",
        "\n",
        "# Display the model's architecture\n",
        "model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "soDE0W_KH8rG"
      },
      "source": [
        "## Save checkpoints during training"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "mRyd5qQQIXZm"
      },
      "source": [
        "You can use a trained model without having to retrain it, or pick-up training where you left off—in case the training process was interrupted. The `tf.keras.callbacks.ModelCheckpoint` callback allows to continually save the model both *during* and at *the end* of training.\n",
        "\n",
        "### Checkpoint callback usage\n",
        "\n",
        "Create a `tf.keras.callbacks.ModelCheckpoint` callback that saves weights only during training:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "IFPuhwntH8VH"
      },
      "outputs": [],
      "source": [
        "checkpoint_path = \"training_1/cp.ckpt\"\n",
        "checkpoint_dir = os.path.dirname(checkpoint_path)\n",
        "\n",
        "# Create a callback that saves the model's weights\n",
        "cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,\n",
        "                                                 save_weights_only=True,\n",
        "                                                 verbose=1)\n",
        "\n",
        "# Train the model with the new callback\n",
        "model.fit(train_images, \n",
        "          train_labels,  \n",
        "          epochs=10,\n",
        "          validation_data=(test_images,test_labels),\n",
        "          callbacks=[cp_callback])  # Pass callback to training\n",
        "\n",
        "# This may generate warnings related to saving the state of the optimizer.\n",
        "# These warnings (and similar warnings throughout this notebook)\n",
        "# are in place to discourage outdated usage, and can be ignored."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "rlM-sgyJO084"
      },
      "source": [
        "This creates a single collection of TensorFlow checkpoint files that are updated at the end of each epoch:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "gXG5FVKFOVQ3"
      },
      "outputs": [],
      "source": [
        "!ls {checkpoint_dir}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "wlRN_f56Pqa9"
      },
      "source": [
        "Create a new, untrained model. When restoring a model from weights-only, you must have a model with the same architecture as the original model. Since it's the same model architecture, you 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):"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "Fp5gbuiaPqCT"
      },
      "outputs": [],
      "source": [
        "# Create a basic model instance\n",
        "model = create_model()\n",
        "\n",
        "# Evaluate the model\n",
        "loss, acc = model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Untrained model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "1DTKpZssRSo3"
      },
      "source": [
        "Then load the weights from the checkpoint and re-evaluate:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "2IZxbwiRRSD2"
      },
      "outputs": [],
      "source": [
        "# Loads the weights\n",
        "model.load_weights(checkpoint_path)\n",
        "\n",
        "# Re-evaluate the model\n",
        "loss,acc = model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "bpAbKkAyVPV8"
      },
      "source": [
        "### Checkpoint callback options\n",
        "\n",
        "The callback provides several options to provide unique names for checkpoints and adjust the checkpointing frequency.\n",
        "\n",
        "Train a new model, and save uniquely named checkpoints once every five epochs:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "mQF_dlgIVOvq"
      },
      "outputs": [],
      "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",
        "# Create a callback that saves the model's weights every 5 epochs\n",
        "cp_callback = tf.keras.callbacks.ModelCheckpoint(\n",
        "    filepath=checkpoint_path, \n",
        "    verbose=1, \n",
        "    save_weights_only=True,\n",
        "    period=5)\n",
        "\n",
        "# Create a new model instance\n",
        "model = create_model()\n",
        "\n",
        "# Save the weights using the `checkpoint_path` format\n",
        "model.save_weights(checkpoint_path.format(epoch=0))\n",
        "\n",
        "# Train the model with the new callback\n",
        "model.fit(train_images, \n",
        "              train_labels,\n",
        "              epochs=50, \n",
        "              callbacks=[cp_callback],\n",
        "              validation_data=(test_images,test_labels),\n",
        "              verbose=0)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "1zFrKTjjavWI"
      },
      "source": [
        "Now, look at the resulting checkpoints and choose the latest one:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "p64q3-V4sXt0"
      },
      "outputs": [],
      "source": [
        "!ls {checkpoint_dir}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "1AN_fnuyR41H"
      },
      "outputs": [],
      "source": [
        "latest = tf.train.latest_checkpoint(checkpoint_dir)\n",
        "latest"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Zk2ciGbKg561"
      },
      "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:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "3M04jyK-H3QK"
      },
      "outputs": [],
      "source": [
        "# Create a new model instance\n",
        "model = create_model()\n",
        "\n",
        "# Load the previously saved weights\n",
        "model.load_weights(latest)\n",
        "\n",
        "# Re-evaluate the model\n",
        "loss, acc = model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "c2OxsJOTHxia"
      },
      "source": [
        "## What are these files?"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "JtdYhvWnH2ib"
      },
      "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",
        "* 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`"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "S_FA-ZvxuXQV"
      },
      "source": [
        "## Manually save weights\n",
        "\n",
        "You saw how to load the weights into a model. Manually saving them is just as simple with the `Model.save_weights` method. By default, `tf.keras`—and `save_weights` in particular—uses the TensorFlow [checkpoint](../../guide/checkpoint.ipynb) format with a `.ckpt` extension (saving in [HDF5](https://js.tensorflow.org/tutorials/import-keras.html) with a `.h5` extension is covered in the [Save and serialize models](../../guide/keras/save_and_serialize#weights-only_saving_in_savedmodel_format) guide):"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "R7W5plyZ-u9X"
      },
      "outputs": [],
      "source": [
        "# Save the weights\n",
        "model.save_weights('./checkpoints/my_checkpoint')\n",
        "\n",
        "# Create a new model instance\n",
        "model = create_model()\n",
        "\n",
        "# Restore the weights\n",
        "model.load_weights('./checkpoints/my_checkpoint')\n",
        "\n",
        "# Evaluate the model\n",
        "loss,acc = model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "kOGlxPRBEvV1"
      },
      "source": [
        "## Save the entire model\n",
        "\n",
        "Call [`model.save`](https://www.tensorflow.org/api_docs/python/tf/keras/Model#save) to save a model's architecture, weights, and training configuration in a single file/folder. This allows you to export a model so it can be used without access to the original Python code*. Since the optimizer-state is recovered, you can resume training from exactly where you left off.\n",
        "\n",
        "Entire model can be saved in two different file formats (`SavedModel` and `HDF5`). It is to be noted that TensorFlow `SavedModel` format is the default file format in TF2.x. However, model can be saved in `HDF5` format. More details on saving entire model in the two file formats is described below.\n",
        "\n",
        "Saving a fully-functional model is very useful—you can load them in TensorFlow.js ([Saved Model](https://www.tensorflow.org/js/tutorials/conversion/import_saved_model), [HDF5](https://www.tensorflow.org/js/tutorials/conversion/import_keras)) and then train and run them in web browsers, or convert them to run on mobile devices using TensorFlow Lite ([Saved Model](https://www.tensorflow.org/lite/convert/python_api#converting_a_savedmodel_), [HDF5](https://www.tensorflow.org/lite/convert/python_api#converting_a_keras_model_))\n",
        "\n",
        "\\*Custom objects (e.g. subclassed models or layers) require special attention when saving and loading. See the **Saving custom objects** section below "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "kPyhgcoVzqUB"
      },
      "source": [
        "### SavedModel format"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "LtcN4VIb7JkK"
      },
      "source": [
        "The SavedModel format is another way to serialize models. Models saved in this format can be restored using `tf.keras.models.load_model` and are compatible with TensorFlow Serving. The [SavedModel guide](https://www.tensorflow.org/guide/saved_model) goes into detail about how to serve/inspect the SavedModel. The section below illustrates the steps to saving and restoring the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "sI1YvCDFzpl3"
      },
      "outputs": [],
      "source": [
        "# Create and train a new model instance.\n",
        "model = create_model()\n",
        "model.fit(train_images, train_labels, epochs=5)\n",
        "\n",
        "# Save the entire model as a SavedModel.\n",
        "!mkdir -p saved_model\n",
        "model.save('saved_model/my_model') "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "iUvT_3qE8hV5"
      },
      "source": [
        "The SavedModel format is a directory containing a protobuf binary and a Tensorflow checkpoint. Inspect the saved model directory:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "sq8fPglI1RWA"
      },
      "outputs": [],
      "source": [
        "# my_model directory\n",
        "!ls saved_model\n",
        "\n",
        "# Contains an assets folder, saved_model.pb, and variables folder.\n",
        "!ls saved_model/my_model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "B7qfpvpY9HCe"
      },
      "source": [
        "Reload a fresh Keras model from the saved model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "0YofwHdN0pxa"
      },
      "outputs": [],
      "source": [
        "new_model = tf.keras.models.load_model('saved_model/my_model')\n",
        "\n",
        "# Check its architecture\n",
        "new_model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "uWwgNaz19TH2"
      },
      "source": [
        "The restored model is compiled with the same arguments as the original model. Try running evaluate and predict with the loaded model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "Yh5Mu0yOgE5J"
      },
      "outputs": [],
      "source": [
        "# Evaluate the restored model\n",
        "loss, acc = new_model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print('Restored model, accuracy: {:5.2f}%'.format(100*acc))\n",
        "\n",
        "print(new_model.predict(test_images).shape)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "SkGwf-50zLNn"
      },
      "source": [
        "### HDF5 format\n",
        "\n",
        "Keras provides a basic save format using the [HDF5](https://en.wikipedia.org/wiki/Hierarchical_Data_Format) standard. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "m2dkmJVCGUia"
      },
      "outputs": [],
      "source": [
        "# Create and train a new model instance.\n",
        "model = create_model()\n",
        "model.fit(train_images, train_labels, epochs=5)\n",
        "\n",
        "# Save the entire model to a HDF5 file.\n",
        "# The '.h5' extension indicates that the model should be saved to HDF5.\n",
        "model.save('my_model.h5') "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "GWmttMOqS68S"
      },
      "source": [
        "Now, recreate the model from that file:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "5NDMO_7kS6Do"
      },
      "outputs": [],
      "source": [
        "# Recreate the exact same model, including its weights and the optimizer\n",
        "new_model = tf.keras.models.load_model('my_model.h5')\n",
        "\n",
        "# Show the model architecture\n",
        "new_model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "JXQpbTicTBwt"
      },
      "source": [
        "Check its accuracy:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "jwEaj9DnTCVA"
      },
      "outputs": [],
      "source": [
        "loss, acc = new_model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print('Restored model, accuracy: {:5.2f}%'.format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "dGXqd4wWJl8O"
      },
      "source": [
        "This technique saves everything:\n",
        "\n",
        "* The weight values\n",
        "* The model's architecture\n",
        "* The model's training configuration(what you passed to compile)\n",
        "* The optimizer and its state, if any (this enables you to restart training where you left)\n",
        "\n",
        "Keras saves models by inspecting the architecture. It is not able to save the `v1.x` optimizers (from `tf.compat.v1.train`) as they aren't compatible with checkpoints. When using those you will need to re-compile the model after loading, and you will lose the state of the optimizer.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "kAUKJQyGqTNH"
      },
      "source": [
        "### Saving custom objects\n",
        "\n",
        "If you are using the SavedModel format, you can skip this section. The key difference between HDF5 and SavedModel is that HDF5 uses object configs to save the model architecture, while SavedModel saves the execution graph. Thus, SavedModels are able to save custom objects like subclassed models and custom layers without requiring the orginal code.\n",
        "\n",
        "To save custom objects to HDF5, you must do the following:\n",
        "\n",
        "1. Define a `get_config` method in your object, and optionally a `from_config` classmethod.\n",
        "  * `get_config(self)` returns a JSON-serializable dictionary of parameters needed to recreate the object.\n",
        "  * `from_config(cls, config)` uses the returned config from `get_config` to create a new object. By default, this function will use the config as initialization kwargs (`return cls(**config)`).\n",
        "2. Pass the object to the `custom_objects` argument when loading the model. The argument must be a dictionary mapping the string class name to the Python class. E.g. `tf.keras.models.load_model(path, custom_objects={'CustomLayer': CustomLayer})`\n",
        "\n",
        "See the [Writing layers and models from scratch](https://www.tensorflow.org/guide/keras/custom_layers_and_models) tutorial for examples of custom objects and `get_config`.\n"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "save_and_load.ipynb",
      "private_outputs": true,
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
{'fraction_non_alphanumeric': 0.15426509633058752, 'fraction_numerical': 0.009377765674994895, 'mean_word_length': 2.0542156149287867, 'pattern_counts': {'":': 694, '<': 49, '<?xml version=': 0, '>': 49, 'https://': 46, 'lorem ipsum': 0, 'www.': 32, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2224535', 'n_tokens_mistral': 19208, 'n_tokens_neox': 18701, 'n_words': 4683}