ValueError: You are trying to load a weight file containing 6 layers into a model with 0
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_model
model = _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, BatchNormalization
def create_model():
kernel_size = 5
pool_size = 2
batchsize = 64
model = 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_model
def 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_batch
else:
img_batch = images[i:]
pos_batch = pos[i:]
yield img_batch, pos_batch
def 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()
python keras neural-network deep-learning
add a comment |
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_model
model = _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, BatchNormalization
def create_model():
kernel_size = 5
pool_size = 2
batchsize = 64
model = 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_model
def 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_batch
else:
img_batch = images[i:]
pos_batch = pos[i:]
yield img_batch, pos_batch
def 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()
python keras neural-network deep-learning
add a comment |
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_model
model = _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, BatchNormalization
def create_model():
kernel_size = 5
pool_size = 2
batchsize = 64
model = 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_model
def 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_batch
else:
img_batch = images[i:]
pos_batch = pos[i:]
yield img_batch, pos_batch
def 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()
python keras neural-network deep-learning
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_model
model = _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, BatchNormalization
def create_model():
kernel_size = 5
pool_size = 2
batchsize = 64
model = 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_model
def 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_batch
else:
img_batch = images[i:]
pos_batch = pos[i:]
yield img_batch, pos_batch
def 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()
python keras neural-network deep-learning
python keras neural-network deep-learning
edited Jan 1 at 10:18


Amir
7,89264173
7,89264173
asked Jan 1 at 6:02
joganjogan
82
82
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Drop
InputLayer
and useinput_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 toHDF5
correctly.
Upgrade your Tensorflow and Keras to the latest version
Fix the interpreter problem as explained here
1
That worked, removing the input layer. Thanks man
– jogan
Jan 1 at 9:51
@jogan If the answer is ok, please mark it as accepted, so other users can benefit from this question and answer.
– Amir
Jan 1 at 18:27
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53993348%2fvalueerror-you-are-trying-to-load-a-weight-file-containing-6-layers-into-a-mode%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Drop
InputLayer
and useinput_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 toHDF5
correctly.
Upgrade your Tensorflow and Keras to the latest version
Fix the interpreter problem as explained here
1
That worked, removing the input layer. Thanks man
– jogan
Jan 1 at 9:51
@jogan If the answer is ok, please mark it as accepted, so other users can benefit from this question and answer.
– Amir
Jan 1 at 18:27
add a comment |
Drop
InputLayer
and useinput_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 toHDF5
correctly.
Upgrade your Tensorflow and Keras to the latest version
Fix the interpreter problem as explained here
1
That worked, removing the input layer. Thanks man
– jogan
Jan 1 at 9:51
@jogan If the answer is ok, please mark it as accepted, so other users can benefit from this question and answer.
– Amir
Jan 1 at 18:27
add a comment |
Drop
InputLayer
and useinput_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 toHDF5
correctly.
Upgrade your Tensorflow and Keras to the latest version
Fix the interpreter problem as explained here
Drop
InputLayer
and useinput_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 toHDF5
correctly.
Upgrade your Tensorflow and Keras to the latest version
Fix the interpreter problem as explained here
edited Jan 1 at 13:50
Keyur Potdar
5,64451632
5,64451632
answered Jan 1 at 8:03


AmirAmir
7,89264173
7,89264173
1
That worked, removing the input layer. Thanks man
– jogan
Jan 1 at 9:51
@jogan If the answer is ok, please mark it as accepted, so other users can benefit from this question and answer.
– Amir
Jan 1 at 18:27
add a comment |
1
That worked, removing the input layer. Thanks man
– jogan
Jan 1 at 9:51
@jogan If the answer is ok, please mark it as accepted, so other users can benefit from this question and answer.
– Amir
Jan 1 at 18:27
1
1
That worked, removing the input layer. Thanks man
– jogan
Jan 1 at 9:51
That worked, removing the input layer. Thanks man
– jogan
Jan 1 at 9:51
@jogan If the answer is ok, please mark it as accepted, so other users can benefit from this question and answer.
– Amir
Jan 1 at 18:27
@jogan If the answer is ok, please mark it as accepted, so other users can benefit from this question and answer.
– Amir
Jan 1 at 18:27
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53993348%2fvalueerror-you-are-trying-to-load-a-weight-file-containing-6-layers-into-a-mode%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown