{"id":5702,"date":"2022-06-22T06:25:28","date_gmt":"2022-06-22T06:25:28","guid":{"rendered":"https:\/\/www.aiproblog.com\/index.php\/2022\/06\/22\/how-to-save-and-load-your-keras-deep-learning-model\/"},"modified":"2022-06-22T06:25:28","modified_gmt":"2022-06-22T06:25:28","slug":"how-to-save-and-load-your-keras-deep-learning-model","status":"publish","type":"post","link":"https:\/\/www.aiproblog.com\/index.php\/2022\/06\/22\/how-to-save-and-load-your-keras-deep-learning-model\/","title":{"rendered":"How to Save and Load Your Keras Deep Learning Model"},"content":{"rendered":"<p>Author: Jason Brownlee<\/p>\n<div>\n<p>Keras is a simple and powerful Python library for deep learning.<\/p>\n<p>Given that deep learning models can take hours, days and even weeks to train, it is important to know how to save and load them from\u00a0disk.<\/p>\n<p>In this post, you will discover how you can <strong>save your Keras models to file<\/strong> and load them up again to make predictions.<\/p>\n<p>After reading this tutorial you will know:<\/p>\n<ul>\n<li>How to save model weights and model architecture in separate files.<\/li>\n<li>How to save model architecture in both YAML and JSON format.<\/li>\n<li>How to save model weights and architecture into a single file for later use.<\/li>\n<\/ul>\n<p><strong>Kick-start your project<\/strong> with my new book <a href=\"https:\/\/machinelearningmastery.com\/deep-learning-with-python\/\">Deep Learning With Python<\/a>, including <em>step-by-step tutorials<\/em> and the <em>Python source code<\/em> files for all examples.<\/p>\n<p>Let\u2019s get started.<\/p>\n<ul>\n<li>\n<strong>Update Mar 2017<\/strong>: Added instructions to install h5py first.<\/li>\n<li>\n<strong>Update Mar\/2017<\/strong>: Updated examples for changes to the Keras API.<\/li>\n<li>\n<strong>Update Mar\/2018<\/strong>: Added alternate link to download the dataset.<\/li>\n<li>\n<strong>Update May\/2019<\/strong>: Added section on saving and loading the model to a single file.<\/li>\n<li>\n<strong>Update Sep\/2019<\/strong>: Added note about using PyYAML version 5.<\/li>\n<li>\n<strong>Update Jun\/2022<\/strong>: Added note about deprecated YAML format and added section about protocol buffer.<\/li>\n<\/ul>\n<div id=\"attachment_2574\" style=\"width: 650px\" class=\"wp-caption aligncenter\">\n<img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-2574\" class=\"size-full wp-image-2574\" src=\"http:\/\/machinelearningmastery.com\/wp-content\/uploads\/2016\/06\/Save-and-Load-Your-Keras-Deep-Learning-Models.jpg\" alt=\"Save and Load Your Keras Deep Learning Models\" width=\"640\" height=\"428\" srcset=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2016\/06\/Save-and-Load-Your-Keras-Deep-Learning-Models.jpg 640w, https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2016\/06\/Save-and-Load-Your-Keras-Deep-Learning-Models-300x201.jpg 300w\" sizes=\"(max-width: 640px) 100vw, 640px\"><\/p>\n<p id=\"caption-attachment-2574\" class=\"wp-caption-text\">How to Save and Load Your Keras Deep Learning Models<br \/>Photo by <a href=\"https:\/\/www.flickr.com\/photos\/art_inthecity\/6346545268\/\">art_inthecity<\/a>, some rights reserved.<\/p>\n<\/div>\n<h2>Tutorial Overview<\/h2>\n<p>If you are new to Keras or deep learning, see this <a href=\"https:\/\/machinelearningmastery.com\/tutorial-first-neural-network-python-keras\/\">step-by-step Keras tutorial<\/a>.<\/p>\n<p>Keras separates the concerns of saving your model architecture and saving your model weights.<\/p>\n<p>Model weights are saved to <a href=\"http:\/\/www.h5py.org\/\">HDF5 format<\/a>. This is a grid format that is ideal for storing multi-dimensional arrays of numbers.<\/p>\n<p>The model structure can be described and saved using two different formats: JSON and YAML.<\/p>\n<p>In this post we are going to look at three examples of saving and loading your model to file:<\/p>\n<ul>\n<li>Save Model to JSON.<\/li>\n<li>Save Model to YAML.<\/li>\n<li>Save Model to HDF5.<\/li>\n<\/ul>\n<p>The first two examples save the model architecture and weights separately. The model weights are saved into a HDF5 format file in all cases.<\/p>\n<p>The examples will use the same simple network trained on the Pima Indians onset of diabetes binary classification dataset. This is a small dataset that contains all numerical data and is easy to work with. You can download this dataset and place it in your working directory with the filename \u201c<em>pima-indians-diabetes.csv<\/em>\u201d (update: <a href=\"https:\/\/raw.githubusercontent.com\/jbrownlee\/Datasets\/master\/pima-indians-diabetes.data.csv\">download from here<\/a>).<\/p>\n<p>Confirm that you have TensorFlow v2.x installed (e.g. v2.9 as of June 2022).<\/p>\n<p><strong>Note<\/strong>: Saving models requires that you have the h5py library installed. It is usually installed as a dependency with TensorFlow. You can also install it easily as follows:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">sudo pip install h5py<\/pre>\n<\/p>\n<div class=\"woo-sc-hr\"><\/div>\n<p><center><\/p>\n<h3>Need help with Deep Learning in Python?<\/h3>\n<p>Take my free 2-week email course and discover MLPs, CNNs and LSTMs (with code).<\/p>\n<p>Click to sign-up now and also get a free PDF Ebook version of the course.<\/p>\n<p><script src=\"https:\/\/embed.lpcontent.net\/leadboxes\/current\/embed.js\" async defer><\/script><button data-leadbox-popup=\"bTgS4zh2NqPUjtGrRXTwLh\" data-leadbox-domain=\"machinelearningmastery.lpages.co\" style=\"background: rgb(255, 215, 18);border-color: rgb(255, 215, 18);border-radius: 20px;color: #FFFFFF;display: inline-block;vertical-align: middle;padding: 16px 32px;min-width: 192px;border: 1px solid rgb(255, 215, 18);font-size: 1rem;font-family: Helvetica, Arial, sans-serif;text-align: center;outline: 0;line-height: 1;cursor: pointer;-webkit-transition: background 0.3s, color 0.3s, border 0.3s;transition: background 0.3s, color 0.3s, border 0.3s;  box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.6);\">Start Your FREE Mini-Course Now<\/button> <\/p>\n<p><\/center><\/p>\n<div class=\"woo-sc-hr\"><\/div>\n<h2>Save Your Neural Network Model to JSON<\/h2>\n<p>JSON is a simple file format for describing data hierarchically.<\/p>\n<p>Keras provides the ability to describe any model using JSON format with a <em>to_json()<\/em> function. This can be saved to file and later loaded via the <em>model_from_json()<\/em> function that will create a new model from the JSON specification.<\/p>\n<p>The weights are saved directly from the model using the <em>save_weights()<\/em> function and later loaded using the symmetrical <em>load_weights()<\/em> function.<\/p>\n<p>The example below trains and evaluates a simple model on the Pima Indians dataset. The model is then converted to JSON format and written to model.json in the local directory. The network weights are written to <em>model.h5<\/em> in the local directory.<\/p>\n<p>The model and weight data is loaded from the saved files and a new model is created. It is important to compile the loaded model before it is used. This is so that predictions made using the model can use\u00a0the appropriate efficient computation from the Keras backend.<\/p>\n<p>The model is evaluated in the same way printing the same evaluation score.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\"># MLP for Pima Indians Dataset Serialize to JSON and HDF5\r\nfrom tensorflow.keras.models import Sequential, model_from_json\r\nfrom tensorflow.keras.layers import Dense\r\nimport numpy\r\nimport os\r\n# fix random seed for reproducibility\r\nnumpy.random.seed(7)\r\n# load pima indians dataset\r\ndataset = numpy.loadtxt(\"pima-indians-diabetes.csv\", delimiter=\",\")\r\n# split into input (X) and output (Y) variables\r\nX = dataset[:,0:8]\r\nY = dataset[:,8]\r\n# create model\r\nmodel = Sequential()\r\nmodel.add(Dense(12, input_dim=8, activation='relu'))\r\nmodel.add(Dense(8, activation='relu'))\r\nmodel.add(Dense(1, activation='sigmoid'))\r\n# Compile model\r\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n# Fit the model\r\nmodel.fit(X, Y, epochs=150, batch_size=10, verbose=0)\r\n# evaluate the model\r\nscores = model.evaluate(X, Y, verbose=0)\r\nprint(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\r\n\r\n# serialize model to JSON\r\nmodel_json = model.to_json()\r\nwith open(\"model.json\", \"w\") as json_file:\r\n    json_file.write(model_json)\r\n# serialize weights to HDF5\r\nmodel.save_weights(\"model.h5\")\r\nprint(\"Saved model to disk\")\r\n\r\n# later...\r\n\r\n# load json and create model\r\njson_file = open('model.json', 'r')\r\nloaded_model_json = json_file.read()\r\njson_file.close()\r\nloaded_model = model_from_json(loaded_model_json)\r\n# load weights into new model\r\nloaded_model.load_weights(\"model.h5\")\r\nprint(\"Loaded model from disk\")\r\n\r\n# evaluate loaded model on test data\r\nloaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\r\nscore = loaded_model.evaluate(X, Y, verbose=0)\r\nprint(\"%s: %.2f%%\" % (loaded_model.metrics_names[1], score[1]*100))<\/pre>\n<\/p>\n<p><strong>Note<\/strong>: Your <a href=\"https:\/\/machinelearningmastery.com\/different-results-each-time-in-machine-learning\/\">results may vary<\/a> given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.<\/p>\n<p>Running this example provides the output below.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">acc: 78.78%\r\nSaved model to disk\r\nLoaded model from disk\r\nacc: 78.78%<\/pre>\n<p>The JSON format of the model looks like the following:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">{  \r\n   \"class_name\":\"Sequential\",\r\n   \"config\":{  \r\n      \"name\":\"sequential_1\",\r\n      \"layers\":[  \r\n         {  \r\n            \"class_name\":\"Dense\",\r\n            \"config\":{  \r\n               \"name\":\"dense_1\",\r\n               \"trainable\":true,\r\n               \"batch_input_shape\":[  \r\n                  null,\r\n                  8\r\n               ],\r\n               \"dtype\":\"float32\",\r\n               \"units\":12,\r\n               \"activation\":\"relu\",\r\n               \"use_bias\":true,\r\n               \"kernel_initializer\":{  \r\n                  \"class_name\":\"VarianceScaling\",\r\n                  \"config\":{  \r\n                     \"scale\":1.0,\r\n                     \"mode\":\"fan_avg\",\r\n                     \"distribution\":\"uniform\",\r\n                     \"seed\":null\r\n                  }\r\n               },\r\n               \"bias_initializer\":{  \r\n                  \"class_name\":\"Zeros\",\r\n                  \"config\":{  \r\n\r\n                  }\r\n               },\r\n               \"kernel_regularizer\":null,\r\n               \"bias_regularizer\":null,\r\n               \"activity_regularizer\":null,\r\n               \"kernel_constraint\":null,\r\n               \"bias_constraint\":null\r\n            }\r\n         },\r\n         {  \r\n            \"class_name\":\"Dense\",\r\n            \"config\":{  \r\n               \"name\":\"dense_2\",\r\n               \"trainable\":true,\r\n               \"dtype\":\"float32\",\r\n               \"units\":8,\r\n               \"activation\":\"relu\",\r\n               \"use_bias\":true,\r\n               \"kernel_initializer\":{  \r\n                  \"class_name\":\"VarianceScaling\",\r\n                  \"config\":{  \r\n                     \"scale\":1.0,\r\n                     \"mode\":\"fan_avg\",\r\n                     \"distribution\":\"uniform\",\r\n                     \"seed\":null\r\n                  }\r\n               },\r\n               \"bias_initializer\":{  \r\n                  \"class_name\":\"Zeros\",\r\n                  \"config\":{  \r\n\r\n                  }\r\n               },\r\n               \"kernel_regularizer\":null,\r\n               \"bias_regularizer\":null,\r\n               \"activity_regularizer\":null,\r\n               \"kernel_constraint\":null,\r\n               \"bias_constraint\":null\r\n            }\r\n         },\r\n         {  \r\n            \"class_name\":\"Dense\",\r\n            \"config\":{  \r\n               \"name\":\"dense_3\",\r\n               \"trainable\":true,\r\n               \"dtype\":\"float32\",\r\n               \"units\":1,\r\n               \"activation\":\"sigmoid\",\r\n               \"use_bias\":true,\r\n               \"kernel_initializer\":{  \r\n                  \"class_name\":\"VarianceScaling\",\r\n                  \"config\":{  \r\n                     \"scale\":1.0,\r\n                     \"mode\":\"fan_avg\",\r\n                     \"distribution\":\"uniform\",\r\n                     \"seed\":null\r\n                  }\r\n               },\r\n               \"bias_initializer\":{  \r\n                  \"class_name\":\"Zeros\",\r\n                  \"config\":{  \r\n\r\n                  }\r\n               },\r\n               \"kernel_regularizer\":null,\r\n               \"bias_regularizer\":null,\r\n               \"activity_regularizer\":null,\r\n               \"kernel_constraint\":null,\r\n               \"bias_constraint\":null\r\n            }\r\n         }\r\n      ]\r\n   },\r\n   \"keras_version\":\"2.2.5\",\r\n   \"backend\":\"tensorflow\"\r\n}<\/pre>\n<\/p>\n<h2>Save Your Neural Network\u00a0Model to YAML<\/h2>\n<p><strong>Note:<\/strong> This method only applies to TensorFlow 2.5 or earlier. If you run it in later versions of TensorFlow, you will see a RuntimeError with the message \u201cMethod <code>model.to_yaml()<\/code> has been removed due to security risk of arbitrary code execution. Please use <code>model.to_json()<\/code> instead.\u201d<\/p>\n<p>This example is much the same as the above JSON example, except the <a href=\"https:\/\/en.wikipedia.org\/wiki\/YAML\">YAML<\/a> format is used for the model specification.<\/p>\n<p>Note, this example assumes that you have PyYAML 5 installed, for example:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">sudo pip install PyYAML<\/pre>\n<p>In this example, the model is described using YAML, saved to file <em>model.yaml<\/em> and later loaded into a new model via the <em>model_from_yaml()<\/em> function.<\/p>\n<p>Weights are handled in the same way as above in HDF5 format as <em>model.h5<\/em>.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\"># MLP for Pima Indians Dataset serialize to YAML and HDF5\r\nfrom tensorflow.keras.models import Sequential, model_from_yaml\r\nfrom tensorflow.keras.layers import Dense\r\nimport numpy\r\nimport os\r\n# fix random seed for reproducibility\r\nseed = 7\r\nnumpy.random.seed(seed)\r\n# load pima indians dataset\r\ndataset = numpy.loadtxt(\"pima-indians-diabetes.csv\", delimiter=\",\")\r\n# split into input (X) and output (Y) variables\r\nX = dataset[:,0:8]\r\nY = dataset[:,8]\r\n# create model\r\nmodel = Sequential()\r\nmodel.add(Dense(12, input_dim=8, activation='relu'))\r\nmodel.add(Dense(8, activation='relu'))\r\nmodel.add(Dense(1, activation='sigmoid'))\r\n# Compile model\r\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n# Fit the model\r\nmodel.fit(X, Y, epochs=150, batch_size=10, verbose=0)\r\n# evaluate the model\r\nscores = model.evaluate(X, Y, verbose=0)\r\nprint(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\r\n\r\n# serialize model to YAML\r\nmodel_yaml = model.to_yaml()\r\nwith open(\"model.yaml\", \"w\") as yaml_file:\r\n    yaml_file.write(model_yaml)\r\n# serialize weights to HDF5\r\nmodel.save_weights(\"model.h5\")\r\nprint(\"Saved model to disk\")\r\n\r\n# later...\r\n\r\n# load YAML and create model\r\nyaml_file = open('model.yaml', 'r')\r\nloaded_model_yaml = yaml_file.read()\r\nyaml_file.close()\r\nloaded_model = model_from_yaml(loaded_model_yaml)\r\n# load weights into new model\r\nloaded_model.load_weights(\"model.h5\")\r\nprint(\"Loaded model from disk\")\r\n\r\n# evaluate loaded model on test data\r\nloaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\r\nscore = loaded_model.evaluate(X, Y, verbose=0)\r\nprint(\"%s: %.2f%%\" % (loaded_model.metrics_names[1], score[1]*100))<\/pre>\n<\/p>\n<p><strong>Note<\/strong>: Your <a href=\"https:\/\/machinelearningmastery.com\/different-results-each-time-in-machine-learning\/\">results may vary<\/a> given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.<\/p>\n<p>Running the example displays the following output.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">acc: 78.78%\r\nSaved model to disk\r\nLoaded model from disk\r\nacc: 78.78%<\/pre>\n<p>The model described in YAML format looks like the following:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">backend: tensorflow\r\nclass_name: Sequential\r\nconfig:\r\n  layers:\r\n  - class_name: Dense\r\n    config:\r\n      activation: relu\r\n      activity_regularizer: null\r\n      batch_input_shape: !!python\/tuple\r\n      - null\r\n      - 8\r\n      bias_constraint: null\r\n      bias_initializer:\r\n        class_name: Zeros\r\n        config: {}\r\n      bias_regularizer: null\r\n      dtype: float32\r\n      kernel_constraint: null\r\n      kernel_initializer:\r\n        class_name: VarianceScaling\r\n        config:\r\n          distribution: uniform\r\n          mode: fan_avg\r\n          scale: 1.0\r\n          seed: null\r\n      kernel_regularizer: null\r\n      name: dense_1\r\n      trainable: true\r\n      units: 12\r\n      use_bias: true\r\n  - class_name: Dense\r\n    config:\r\n      activation: relu\r\n      activity_regularizer: null\r\n      bias_constraint: null\r\n      bias_initializer:\r\n        class_name: Zeros\r\n        config: {}\r\n      bias_regularizer: null\r\n      dtype: float32\r\n      kernel_constraint: null\r\n      kernel_initializer:\r\n        class_name: VarianceScaling\r\n        config:\r\n          distribution: uniform\r\n          mode: fan_avg\r\n          scale: 1.0\r\n          seed: null\r\n      kernel_regularizer: null\r\n      name: dense_2\r\n      trainable: true\r\n      units: 8\r\n      use_bias: true\r\n  - class_name: Dense\r\n    config:\r\n      activation: sigmoid\r\n      activity_regularizer: null\r\n      bias_constraint: null\r\n      bias_initializer:\r\n        class_name: Zeros\r\n        config: {}\r\n      bias_regularizer: null\r\n      dtype: float32\r\n      kernel_constraint: null\r\n      kernel_initializer:\r\n        class_name: VarianceScaling\r\n        config:\r\n          distribution: uniform\r\n          mode: fan_avg\r\n          scale: 1.0\r\n          seed: null\r\n      kernel_regularizer: null\r\n      name: dense_3\r\n      trainable: true\r\n      units: 1\r\n      use_bias: true\r\n  name: sequential_1\r\nkeras_version: 2.2.5<\/pre>\n<\/p>\n<h2>Save Model Weights and Architecture Together<\/h2>\n<p>Keras also supports a simpler interface to save both the model weights and model architecture together into a single H5 file.<\/p>\n<p>Saving the model in this way includes everything we need to know about the model, including:<\/p>\n<ul>\n<li>Model weights.<\/li>\n<li>Model architecture.<\/li>\n<li>Model compilation details (loss and metrics).<\/li>\n<li>Model optimizer state.<\/li>\n<\/ul>\n<p>This means that we can load and use the model directly, without having to re-compile it as we did in the examples above.<\/p>\n<p><strong>Note<\/strong>: this is the preferred way for saving and loading your Keras model.<\/p>\n<h3>How to Save a Keras Model<\/h3>\n<p>You can save your model by calling the <em>save()<\/em> function on the model and specifying the filename.<\/p>\n<p>The example below demonstrates this by first fitting a model, evaluating it and saving it to the file <em>model.h5<\/em>.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\"># MLP for Pima Indians Dataset saved to single file\r\nfrom numpy import loadtxt\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras.layers import Dense\r\n# load pima indians dataset\r\ndataset = loadtxt(\"pima-indians-diabetes.csv\", delimiter=\",\")\r\n# split into input (X) and output (Y) variables\r\nX = dataset[:,0:8]\r\nY = dataset[:,8]\r\n# define model\r\nmodel = Sequential()\r\nmodel.add(Dense(12, input_dim=8, activation='relu'))\r\nmodel.add(Dense(8, activation='relu'))\r\nmodel.add(Dense(1, activation='sigmoid'))\r\n# compile model\r\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n# Fit the model\r\nmodel.fit(X, Y, epochs=150, batch_size=10, verbose=0)\r\n# evaluate the model\r\nscores = model.evaluate(X, Y, verbose=0)\r\nprint(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\r\n# save model and architecture to single file\r\nmodel.save(\"model.h5\")\r\nprint(\"Saved model to disk\")<\/pre>\n<\/p>\n<p><strong>Note<\/strong>: Your <a href=\"https:\/\/machinelearningmastery.com\/different-results-each-time-in-machine-learning\/\">results may vary<\/a> given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.<\/p>\n<p>Running the example fits the model, summarizes the models performance on the training dataset and saves the model to file.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">acc: 77.73%\r\nSaved model to disk<\/pre>\n<p>We can later load this model from file and use it.<\/p>\n<p>Note that in Keras library, there is another function doing the same, as follows:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# equivalent to: model.save(\"model.h5\")\r\nfrom tensorflow.keras.models import save_model\r\nsave_model(model, \"model.h5\")<\/pre>\n<\/p>\n<h3>How to Load a Keras Model<\/h3>\n<p>Your saved model can then be loaded later by calling the <code>load_model()<\/code> function and passing the filename. The function returns the model with the same architecture and weights.<\/p>\n<p>In this case, we load the model, summarize the architecture and evaluate it on the same dataset to confirm the weights and architecture are the same.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\"># load and evaluate a saved model\r\nfrom numpy import loadtxt\r\nfrom tensorflow.keras.models import load_model\r\n\r\n# load model\r\nmodel = load_model('model.h5')\r\n# summarize model.\r\nmodel.summary()\r\n# load dataset\r\ndataset = loadtxt(\"pima-indians-diabetes.csv\", delimiter=\",\")\r\n# split into input (X) and output (Y) variables\r\nX = dataset[:,0:8]\r\nY = dataset[:,8]\r\n# evaluate the model\r\nscore = model.evaluate(X, Y, verbose=0)\r\nprint(\"%s: %.2f%%\" % (model.metrics_names[1], score[1]*100))<\/pre>\n<p>Running the example first loads the model, prints a summary of the model architecture then evaluates the loaded model on the same dataset.<\/p>\n<p><strong>Note<\/strong>: Your <a href=\"https:\/\/machinelearningmastery.com\/different-results-each-time-in-machine-learning\/\">results may vary<\/a> given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.<\/p>\n<p>The model achieves the same accuracy score which in this case is 77%.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">_________________________________________________________________\r\nLayer (type)                 Output Shape              Param #   \r\n=================================================================\r\ndense_1 (Dense)              (None, 12)                108       \r\n_________________________________________________________________\r\ndense_2 (Dense)              (None, 8)                 104       \r\n_________________________________________________________________\r\ndense_3 (Dense)              (None, 1)                 9         \r\n=================================================================\r\nTotal params: 221\r\nTrainable params: 221\r\nNon-trainable params: 0\r\n_________________________________________________________________\r\n\r\nacc: 77.73%<\/pre>\n<\/p>\n<h3>Protocol Buffer Format<\/h3>\n<p>While saving and loading a Keras model using HDF5 format is the recommended way, TensorFlow supports yet another format, the <em><a href=\"https:\/\/developers.google.com\/protocol-buffers\">protocol buffer<\/a><\/em>. It is considered faster to save and load a protocol buffer format but doing so will produce multiple files. The syntax is the same, except that we do not need to provide the <code>.h5<\/code> extension to the filename:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\"># save model and architecture to single file\r\nmodel.save(\"model\")\r\n\r\n# ... later\r\n\r\n# load model\r\nmodel = load_model('model')\r\n# print summary\r\nmodel.summary()<\/pre>\n<p>These will create a directory \u201cmodel\u201d with the following files:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">model\/\r\n|-- assets\/\r\n|-- keras_metadata.pb\r\n|-- saved_model.pb\r\n`-- variables\/\r\n    |-- variables.data-00000-of-00001\r\n    `-- variables.index<\/pre>\n<p>This is also the format we used to save a model in TensorFlow v1.x. You may encounter this when you download a pretrained model from <a href=\"https:\/\/www.tensorflow.org\/hub\">TensorFlow Hub<\/a>.<\/p>\n<h2>Further Reading<\/h2>\n<ul>\n<li>\n<a href=\"https:\/\/keras.io\/getting-started\/faq\/#how-can-i-save-a-keras-model\">How can I save a Keras model?<\/a> in the Keras documentation.<\/li>\n<li>\n<a href=\"https:\/\/keras.io\/models\/about-keras-models\/\">About Keras models<\/a> in the\u00a0Keras documentation.<\/li>\n<\/ul>\n<h2>Summary<\/h2>\n<p>In this post, you discovered how to serialize your Keras deep learning models.<\/p>\n<p>You learned\u00a0how you can save your trained models to files and later load them up and use them to make predictions.<\/p>\n<p>You also learned that model weights are easily stored using \u00a0HDF5 format and that the network structure can be saved in either JSON or YAML format.<\/p>\n<p>Do you have any questions about saving your deep learning models or about this post?<br \/>\nAsk your questions in the comments and I will do my best to answer them.<\/p>\n<p>The post <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/save-load-keras-deep-learning-models\/\">How to Save and Load Your Keras Deep Learning Model<\/a> appeared first on <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/\">Machine Learning Mastery<\/a>.<\/p>\n<\/div>\n<p><a href=\"https:\/\/machinelearningmastery.com\/save-load-keras-deep-learning-models\/\">Go to Source<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Author: Jason Brownlee Keras is a simple and powerful Python library for deep learning. Given that deep learning models can take hours, days and even [&hellip;] <span class=\"read-more-link\"><a class=\"read-more\" href=\"https:\/\/www.aiproblog.com\/index.php\/2022\/06\/22\/how-to-save-and-load-your-keras-deep-learning-model\/\">Read More<\/a><\/span><\/p>\n","protected":false},"author":1,"featured_media":5703,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_bbp_topic_count":0,"_bbp_reply_count":0,"_bbp_total_topic_count":0,"_bbp_total_reply_count":0,"_bbp_voice_count":0,"_bbp_anonymous_reply_count":0,"_bbp_topic_count_hidden":0,"_bbp_reply_count_hidden":0,"_bbp_forum_subforum_count":0,"footnotes":""},"categories":[24],"tags":[],"_links":{"self":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/5702"}],"collection":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/comments?post=5702"}],"version-history":[{"count":0,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/5702\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media\/5703"}],"wp:attachment":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media?parent=5702"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/categories?post=5702"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/tags?post=5702"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}