user12096782
user12096782

Reputation:

How to fix ("ValueError: You are trying to load a weight file containing 16 layers into a model with 0 layers")

I'm using vgg16 like this:

model = VGG16()
data, labels = ReadImages(TRAIN_DIR)

vgg16 = VGG16()

model = Sequential()

#Converting VGG16 into Sequential model
for layer in vgg16.layers[:-1]:
    model.add(layer)

#Freezing all layers except last layer for transfer learning
for layer in model.layers:
    layer.trainable = False

#Adding custom softmax layer
model.add(Dense(1,activation='sigmoid'))

#Compiling our model
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])

model.fit(np.array(data), np.array(labels), batch_size=32, epochs=3)

model.save('model.h5')

and when I tried to load this model in another py file..:

model = load_model('model.h5')

I'd already tried load_weights and throws an error too

... returns this error:

ValueError: You are trying to load a weight file containing 16 layers into a model with 0 layers

What should I do to load this model to make my predictions?

versions: keras 2.2.4 tensorflow 1.14.0

Upvotes: 3

Views: 4632

Answers (2)

brandonanhorn
brandonanhorn

Reputation: 1

This issue has been solved in newer versions of TensorFlow

simply upgrade your TensorFlow: pip install tensorflow --upgrade

Upvotes: -1

Manoj Mohan
Manoj Mohan

Reputation: 6054

Known issue: https://github.com/keras-team/keras/issues/10417

There are three options: 1. Recreate the model architecture and use 'load_weights'. This is good if you only want to do predictions. 2. Downgrade to Keras version 2.1.6. 3. A workaround available at this link https://github.com/keras-team/keras/issues/10417#issuecomment-435620108. I adapted this for VGG16. This updates the h5 file.

def fix_layer0(filename, batch_input_shape, dtype):
    with h5py.File(filename, 'r+') as f:
        model_config = json.loads(f.attrs['model_config'].decode('utf-8'))
        layer0 = model_config['config']['layers'][0]['config']
        layer0['batch_input_shape'] = batch_input_shape
        layer0['dtype'] = dtype
        f.attrs['model_config'] = json.dumps(model_config).encode('utf-8')

fix_layer0('model.h5', [None, 224, 224, 3], 'float32')

loaded_model = load_model('model.h5')

Upvotes: 1

Related Questions