EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials Keras Tutorial Keras Save Model
Secondary Sidebar
Keras Tutorial
  • Basic
    • What is Keras?
    • Keras Install
    • Keras Applications
    • Keras Sequential
    • Keras Model Predict
    • Keras Save Model
    • Keras conv2D
    • Keras ImageDataGenerator
    • Keras input
    • Keras Datasets
    • Keras Early Stopping
    • Keras input
    • Keras Model Save
    • Keras LSTM Example
    • Keras Flatten
    • Keras Optimizers
    • Keras Layers
    • Keras Dense
    • Keras fit
    • Keras Model
    • Keras Metrics
    • Keras Batch Normalization
    • Keras CNN
    • Keras predict
    • Keras Dropout
    • Keras Embedding
    • Keras LSTM
    • Keras GPU
    • Keras Tuner
    • Keras VGG16
    • Keras Generator
    • Keras Pre-trained Models
    • Keras Custom Loss Function
    • keras.utils.to_categorical
    • Keras Neural Network
    • Keras Preprocessing
    • Keras Regularization
    • Keras Softmax
    • Keras Regression
    • Keras MaxPooling2D
    • Keras U-Net
    • Keras Initializers
    • Keras Transformer
    • Keras Data Augmentation
    • Keras ResNet50
    • Keras Verbose
    • Keras Plot Model
    • Keras OCR
    • Keras Utils Sequence
    • Keras Binary Classification
    • Keras Padding
    • UpSampling2d
    • Keras EfficientNet
    • Keras pad_sequences

Keras Save Model

Keras Save Model

Introduction to Keras Save Model

keras save model is the process of saving the complete keras model that we have created along with all its components. In this article, we will have a look at the keras save model by studying keras save model overviews, How to use save model keras, saving and loading the model, keras save model explains, method and conclusion about the same.

Overview on keras save model

There are various components present inside the keras model that we will need to consider while saving the complete model. The list of the components of keras model is as given below –

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

  • The connections between the layers and the total layers present in the model along with its description are specified by the configurations and architecture of the keras model.
  • The state of the model contains the details regarding the set of values of weights corresponding to our model.
  • The optimizer of the model is defined only after the compilation of your keras model.
  • Metrics and losses set which is defined by giving a call to the add_metric() method or add_loss() method or simply compiling the keras model.

How to use save model keras?

The API used for saving the model is tensorflow. Keras. models. Save_model() and for the loading of the model, we will be using tensorflow.keras.models.load_model()

The most standard method for saving the model is in the SavedModel format. However, we can switch to h5 format simply by passing the save_format = h5 to the API method of save () or by passing the .keras or .h5 ending filename to the method of save() API.

Let us take one example to understand the saving of the keras model by using the SavedModel format which is quite comprehensive as it helps in saving various components of the model including its weights, subgraphs of call functions, and architecture. This makes the keras model capable of restoring the custom objects along with the layers that are built-in inside the model.

def retrieveModel():

# Model creation in Keras
inputValues = keras.Input(shape=(32,))
outputValues = keras.layers.Dense(1)(inputValues)
sampleEducbaModel = keras.Model(inputValues, outputValues)
sampleEducbaModel.compile(optimizer="adam", loss="mean_squared_error")
return sampleEducbaModel
sampleEducbaModel = retrieveModel()
# Model training
inputValueForTesting = np.random.random((128, 32))
valueForTarget = np.random.random((128, 1))
sampleEducbaModel.fit(inputValueForTesting, valueForTarget)
# when we give a call to the save() method, it leads to creation of new folder named my_sampleEducbaModel
sampleEducbaModel.save("my_sampleEducbaModel")
# We can reconstruct the model which is identical
reconstructed_sampleEducbaModel = keras.sampleEducbaModels.load_sampleEducbaModel("my_sampleEducbaModel")
# Testing the working of model
np.testing.assert_allclose(
sampleEducbaModel.predict(inputValueForTesting), reconstructed_sampleEducbaModel.predict(inputValueForTesting)
)
# Resuming the training as the reconstructed sampleEducbaModel is already compiled and contains optimizer
reconstructed_sampleEducbaModel.fit(inputValueForTesting, valueForTarget)

The output of the execution of the above program is –

Keras Save Model output 1

When we give the call to sampleEducbaModel.save(‘my_sampleEducbaModel’), new folder having the name my_sampleEducbaModel is created which will have the following in it when listed by using the below command –

Ls my_sampleEducbaModel

Output of above command is –

Keras Save Model output 2

Saved_model.pb will contain all the configurations related to the training and architecture of the model containing losses, optimizers, and metrics.  The directory named variables will contain the values of weights. You can refer to this link for additional details.

Saving and loading the model

For saving the model, we can simply use the save () method. Let’s take one sample example, if the model created is of the functional model, sequential model, or model subclass then we can simply get it and then save the model. If the model name is sampleEducbaModel then we can save it by using the below statement –

sampleEducbaModel.save(‘location or path where the model is to be saved’)

For loading the model, we can write the following code snippet –

From tensorflow import keras
sampleEducbaModel = keras.models.load_model(‘location from where the model is to be loaded’)

When we sample the complete model we will follow the below process –

  • The configuration and architecture of the model
  • Weight values of the model that were learned while the training period.
  • Compilation information of the model if the method of compile() was called in the model.
  • The state of the model and the optimizer will help you to resume the training from the point of time where you left it.

Keras Save Model Explaination

There is a provision of API in keras which allows saving of either individually selected components from the above or all of the components to the disk at once. The saving of keras model can be done by using either of the following methods –

  • The standard practice followed is saving the whole thing into the single archive by using the keras H5 format which is an older methodology or saved model format of tensorflow.
  • Only the configuration or architecture can be saved in the format of a JSON file.
  • Only the weights of the model can be saved which is mostly done while model training.

Method

The save method has the following syntax –

NameOfModel.save( filepath, overwrite = True, include_optimizer = True, save_format = None, signatures = None, options = None, save_traces = True)

The arguments or parameters used in the above syntax are described here –

  • File path – It is a strng value specifying the location with its complete path where we want to save the model or SavedModel or H5 file.
  • Overwrite = It is a Boolean value that specifies if we want to overwrite silently the existing content of the file at the specified location or manual prompt provision should be given.
  • Include optimizer – If we want the whole state of the optimizer to be saved together, we can set this value of the argument to true.
  • Save format – It helps in the specification of the file format in which the model should be saved. It can have either h5 or tf format which stands for HDF5 format or SavedModel of tensorflow. The default value when not specified is set to tf in TF tensorflow 2.X and in tensorflow TF 1.X to h5 value.
  • Signatures – It specifies the signature to be used while saving the model which is applicable only if you are using tf format.

Conclusion

Keras Save model is the API method available which enables you to save all the components at once or only selective ones in the SavedModel format or HDF5 format.

Recommended Articles

This is a guide to Keras Save Model. Here we discuss the keras save model by studying keras save model overviews, How to use save model keras. You may also look at the following articles to learn more –

  1. TensorFlow Keras Model
  2. PyTorch ResNet
  3. tensorflow flatten
  4. TensorFlow estimator
Popular Course in this category
Keras Training (2 Courses, 8 Projects)
  2 Online Courses |  8 Hands-on Project |  24+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more