Python 使用load_模型或load_权重时的值错误

Python 使用load_模型或load_权重时的值错误,python,keras,Python,Keras,我建立了一个简单的lenet模型: def get_lenet(): kernel_size = (5, 5) model = Sequential() # each image is 28x28 model.add(Conv2D(32, kernel_size, activation='relu')) # now 24x24 model.add(MaxPool2D()) # 12x12 model.add(Conv2D(64, kernel_siz

我建立了一个简单的lenet模型:

def get_lenet():
    kernel_size = (5, 5)
    model = Sequential()  # each image is 28x28
    model.add(Conv2D(32, kernel_size, activation='relu'))  # now 24x24
    model.add(MaxPool2D())  # 12x12
    model.add(Conv2D(64, kernel_size, activation='relu'))  # 8x8
    model.add(MaxPool2D())  # 4x4
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dense(10, activation='softmax'))
    return model
编译和培训都进行得很顺利,然后我保存模型:

model.save_weights('w.h5')
with open('model_architecture.json', 'w') as f:
    f.write(model.to_json())
稍后,当尝试加载时

with open('model_architecture.json', 'r') as f:
    model = model_from_json(f.read())
model.load_weights('w.h5)
我得到以下错误:

ValueError: You are trying to load a weight file containing 4 layers into a model with 0 layers.
使用save_模型时也会出现相同的错误。
有人有什么想法吗?

你有没有尝试过这篇文章的答案,我刚刚遇到了同样的问题,并通过明确声明层的输入维度解决了这个问题。我无法运行您的代码,因为我无法导入Conv2D。但是,您可以通过修改层来尝试,例如:model.add(稠密(10,activation='softmax',input_dim=128))。希望它也能对你有用。