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

2024/9/23 12:28:51

I have a simple keras model. After the model is saved. I am unable to load the model. This is the error I get after instantiating the model and trying to load weights:

Using TensorFlow backend.
Traceback (most recent call last):File "test.py", line 4, in <module>model = load_model("test.h5")File "/usr/lib/python3.7/site-packages/keras/engine/saving.py", line 419, in load_modelmodel = _deserialize_model(f, custom_objects, compile)File "/usr/lib/python3.7/site-packages/keras/engine/saving.py", line 258, in _deserialize_model
.format(len(layer_names), len(filtered_layers))ValueError: You are trying to load a weight file containing 6 layers into a model with 0 layers

For instantiating the model and using model.load_weights and doing a model summary. I get None when I print the model using print(model)

Traceback (most recent call last):
File "test.py", line 7, in <module>print(model.summary())
AttributeError: 'NoneType' object has no attribute 'summary'

Here is my Network:

from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, InputLayer, Flatten,    Dense, BatchNormalizationdef create_model():kernel_size = 5pool_size = 2batchsize = 64model = Sequential()model.add(InputLayer((36, 120, 1)))model.add(Conv2D(filters=20, kernel_size=kernel_size,    activation='relu', padding='same'))model.add(BatchNormalization())model.add(MaxPooling2D(pool_size))model.add(Conv2D(filters=50, kernel_size=kernel_size, activation='relu', padding='same'))model.add(BatchNormalization())model.add(MaxPooling2D(pool_size))model.add(Flatten())model.add(Dense(120, activation='relu'))model.add(Dense(2, activation='relu'))return model

Training procedure script:

import numpy as np
from keras import optimizers
from keras import losses
from sklearn.model_selection import train_test_split
from model import create_modeldef data_loader(images, pos):while(True):for i in range(0, images.shape[0], 64):if (i+64) < images.shape[0]:img_batch = images[i:i+64]pos_batch = pos[i:i+64]yield img_batch, pos_batchelse:img_batch = images[i:]pos_batch = pos[i:]yield img_batch, pos_batchdef main():model = create_model()sgd = optimizers.Adadelta(lr=0.01, rho=0.95, epsilon=None, decay=0.0)model.compile(loss=losses.mean_squared_error, optimizer=sgd)print("traning")data = np.load("data.npz")images = data['images']pos = data['pos']x_train, x_test, y_train, y_test = train_test_split(images, pos, test_size=0.33, random_state=42)model.fit_generator(data_loader(x_train, y_train), steps_per_epoch=x_train.shape[0]//64, validation_data=data_loader(x_test, y_test), \validation_steps = x_test.shape[0]//64, epochs=1)model.save('test.h5')model.save_weights('test_weights.h5')print("training done")if __name__ == '__main__':main()
Answer
  1. Drop InputLayer and use input_shape in first layer. Your code will be similar to:

    model = Sequentional()
    model.add(Conv2D(filters=20,..., input_shape=(36, 120, 1)))

    It seems models with InputLayer are not serialized to HDF5 correctly.

  2. Upgrade your Tensorflow and Keras to the latest version

  3. Fix the interpreter problem as explained here

https://en.xdnf.cn/q/71825.html

Related Q&A

cProfile with imports

Im currently in the process of learn how to use cProfile and I have a few doubts.Im currently trying to profile the following script:import timedef fast():print("Fast!")def slow():time.sleep(…

Python AWS Lambda 301 redirect

I have a lambda handler written in Python and I wish to perform a 301 redirect to the browser. I have no idea how I can configure the response Location header (or the status code) -- the documentation …

Google Authenticator code does not match server generated code

BackgroundIm currently working on a two-factor authentication system where user are able to authenticate using their smartphone. Before the user can make use of their device they need to verify it firs…

Gekko Non-Linear optimization, object type error in constraint function evaluating if statement

Im trying to solve a non-linear optimization problem. Ive duplicated my issue by creating the code below. Python returns TypeError: object of type int has no len(). How can I include an IF statement in…

Store large dictionary to file in Python

I have a dictionary with many entries and a huge vector as values. These vectors can be 60.000 dimensions large and I have about 60.000 entries in the dictionary. To save time, I want to store this aft…

Python: override __str__ in an exception instance

Im trying to override the printed output from an Exception subclass in Python after the exception has been raised and Im having no luck getting my override to actually be called.def str_override(self):…

How hide/show a field upon selection of a radio button in django admin?

models.pyfrom django.db import models from django.contrib.auth.models import UserSTATUS_CHOICES = ((1, Accepted),(0, Rejected),) class Leave(models.Model):----------------status = models.IntegerField(c…

format/round numerical legend label in GeoPandas

Im looking for a way to format/round the numerical legend labels in those maps produced by .plot() function in GeoPandas. For example:gdf.plot(column=pop2010, scheme=QUANTILES, k=4)This gives me a lege…

Python pickle crash when trying to return default value in __getattr__

I have a dictionary like class that I use to store some values as attributes. I recently added some logic(__getattr__) to return None if an attribute doesnt exist. As soon as I did this pickle crashe…

How to download google source code for android

As you know, there is a list of several hundred projects in https://android.googlesource.com/. Id like to download them all in windows machine. According to Googles document,To install, initialize, and…