python - Keras try save and load model error You are trying to load a weight file containing 16 layers into a model with 0 层数

标签 python tensorflow keras deep-learning theano

我正在尝试在 Keras 中微调和保存模型并加载它,但出现此错误:
值错误:您正在尝试将包含 16 层的权重文件加载到具有 0 层的模型中。
我尝试了另一种数字模型我让它保存和加载模式工作没有错误 当我尝试采用 vgg16 时,它给出了错误
我想要加载模型但由于此错误而无法加载。谁能帮忙?

import keras
from  keras.models import Sequential,load_model,model_from_json

from keras import backend as K
from keras.layers import Activation,Conv2D,MaxPooling2D,Dropout
from keras.layers.core import Dense,Flatten
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import *
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
import itertools
from sklearn.metrics import confusion_matrix

import numpy as np
train_path='dataset/train'
test_path='dataset/test'
valid_path='dataset/valid'
train_batches=ImageDataGenerator()
.flow_from_directory(train_path,batch_size=1,target_size=(224,224),classes= 
 ['dog','cat'])
valid_batches=ImageDataGenerator()
.flow_from_directory(valid_path,batch_size=4,target_size=(224,224),classes= 
['dog','cat'])
test_batches=ImageDataGenerator()
.flow_from_directory(test_path,target_size=(224,224),classes=['dog','cat'])

 vgg16_model=keras.applications.vgg16.VGG16();

vgg16_model.summary()

type(vgg16_model)

model=Sequential()
for layer in vgg16_model.layers[:-1]:
    model.add(layer)




for layer in model.layers:
    layer.trainable=False

 model.add(Dense(2,activation='softmax'))


 model.compile(Adam(lr=.0001),loss='categorical_crossentropy',metrics= 
 ['accuracy'])
model.fit_generator(train_batches,validation_data=valid_batches,epochs=1)


model.save('test.h5')
model.summary()
xx=load_model('test.h5')

最佳答案

我以不同的方式加载模型,四处寻找解决方案,我遇到了同样的问题。现在应用我训练过的模型。最后我使用 VGG16 作为模型并使用我自己训练的 h5 权重,太棒了!

weights_model='C:/Anaconda/weightsnew2.h5'  # my already trained 
weights .h5
vgg=applications.vgg16.VGG16()
cnn=Sequential()
for capa in vgg.layers:
    cnn.add(capa)
cnn.layers.pop()
for layer in cnn.layers:
    layer.trainable=False
cnn.add(Dense(2,activation='softmax'))  

cnn.load_weights(weights_model)

def predict(file):
    x = load_img(file, target_size=(longitud, altura)) 
    x = img_to_array(x)                            
    x = np.expand_dims(x, axis=0)
    array = cnn.predict(x)     
    result = array[0]
    respuesta = np.argmax(result) 
    if respuesta == 0:
        print("Gato")
    elif respuesta == 1:
        print("Perro")

关于python - Keras try save and load model error You are trying to load a weight file containing 16 layers into a model with 0 层数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51544666/

相关文章:

python - 初学者问题,使用 sklearn,保存模型并测试单个数据帧

python - 在Python中的嵌套函数之间共享局部变量

python - 索引错误: list index out of range: I can uderstand why this error happens

python - 编译支持GPU的Tensorflow时,遇到CUDA_TOOLKIT_PATH未绑定(bind)变量

javascript - WebGL:使用 tf.browser.fromPixels 转换本地镜像时出现 INVALID_VALUE

python - 将Keras模型HDF5文件存储到SQL数据库

python - 在 Keras 中实现 Rprop 算法

python - 动态选择函数

python - ValueError : Error when checking target: expected time_distributed_7 to have 4 dimensions, 但得到形状为 (500, 18, 64) 的数组

python - tensorflow ffmpeg contrib 输出