Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tf.keras.models.save_model and optimizer warning

I created a Sequential model using tf.keras as follows:

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(8, input_dim=4))
model.add(tf.keras.layers.Dense(3, activation=tf.nn.softmax))

opt = tf.train.AdamOptimizer(learning_rate=0.001)
model.compile(optimizer=opt, loss="categorical_crossentropy", metrics=["accuracy"])

model.summary()

After that, I created a training process using train_on_batch:

EPOCHS=50
for epoch in range(EPOCHS):
  for metrics, labels in dataset:
    # Calculate training loss and accuracy
    tr_loss, tr_accuracy = model.train_on_batch(metrics, labels)

When I try to save the model, I receive a warning. I can't understand why, because I included the optimizer as part of the model.compile:

tf.keras.models.save_model(
    model,
    "./model/iris_model.h5",
    overwrite=True,
    include_optimizer=True
)

WARNING:tensorflow:TensorFlow optimizers do not make it possible to access optimizer attributes or optimizer state after instantiation. As a result, we cannot save the optimizer as part of the model save file.You will have to compile your model again after loading it. Prefer using a Keras optimizer instead (see keras.io/optimizers).

The TF version I used is 1.9.0-rc2.

like image 845
Nicolas Bortolotti Avatar asked Jul 09 '18 19:07

Nicolas Bortolotti


People also ask

What does an optimiser do in Keras?

Optimizers are Classes or methods used to change the attributes of your machine/deep learning model such as weights and learning rate in order to reduce the losses. Optimizers help to get results faster.

How do you predict a saved model in Keras?

The first step is to import your model using load_model method. Then you have to compile the model in order to make predictions. Now you can predict results for a new entry image. You do not need to compile anymore.

What is H5 file in Keras?

H5 is a file format to store structured data, it's not a model by itself. Keras saves models in this format as it can easily store the weights and model configuration in a single file.

What is tf Keras optimizers Adam?

Adam optimization is a stochastic gradient descent method that is based on adaptive estimation of first-order and second-order moments.


1 Answers

As the warning says the Tensorflow optimizers cannot be saved when saving the model. Instead, use the optimizers provided by Keras:

opt = tf.keras.optimizers.Adam(lr=0.001)
like image 97
today Avatar answered Oct 04 '22 20:10

today