Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't load my trained h5 model with load.models(), how do I fix this error?

So I think tensorflow.keras and the independant keras packages are in conflict and I can't load my model, which I have made with transfer learning. Import in the CNN ipynb:

!pip install tensorflow-gpu==2.0.0b1

import tensorflow as tf
from tensorflow import keras
print(tf.__version__) 

Loading this pretrained model

base_model = keras.applications.xception.Xception(weights="imagenet",
                                              include_top=False)
avg = keras.layers.GlobalAveragePooling2D()(base_model.output)
output = keras.layers.Dense(n_classes, activation="softmax")(avg)
model = keras.models.Model(inputs=base_model.input, outputs=output)

Saving with:

model.save('Leavesnet Model 2.h5')

Then in the new ipynb for the already trained model (the imports are the same as in the CNN ipynb:

from keras.models import load_model

model =load_model('Leavesnet Model.h5')

I get the error:

AttributeError                            Traceback (most recent call last)
<ipython-input-4-77ca5a1f5f24> in <module>()
      2 from keras.models import load_model
      3 
----> 4 model =load_model('Leavesnet Model.h5')

13 frames
/usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py in placeholder(shape, ndim, dtype, sparse, name)
    539         x = tf.sparse_placeholder(dtype, shape=shape, name=name)
    540     else:
--> 541         x = tf.placeholder(dtype, shape=shape, name=name)
    542     x._keras_shape = shape
    543     x._uses_learning_phase = False

AttributeError: module 'tensorflow' has no attribute 'placeholder' 

I think there might be a conflict between tf.keras and the independant keras, can someone help me out?

like image 520
Monlist Avatar asked Mar 03 '23 11:03

Monlist


2 Answers

Yes, there is a conflict between tf.keras and keras packages, you trained the model using tf.keras but then you are loading it with the keras package. That is not supported, you should use only one version of this package.

The specific problem is that you are using TensorFlow 2.0, but the standalone keras package does not support TensorFlow 2.0 yet.

like image 135
Dr. Snoopy Avatar answered Apr 28 '23 01:04

Dr. Snoopy


Try to replace

from keras.models import load_model
model =load_model('Leavesnet Model.h5')

with

model = tf.keras.models.load_model(model_path)

It works for me, and I am using: tensorflow version: 2.0.0 keras version: 2.3.1

You can check the following: https://www.tensorflow.org/api_docs/python/tf/keras/models/load_model?version=stable

like image 20
Majd Al-okeh Avatar answered Apr 28 '23 00:04

Majd Al-okeh