Python 3.x ValueError:您试图将包含58层的权重文件加载到包含55层的模型中

Python 3.x ValueError:您试图将包含58层的权重文件加载到包含55层的模型中,python-3.x,tensorflow,keras,transfer-learning,Python 3.x,Tensorflow,Keras,Transfer Learning,我训练了我的模型,并以.h5格式保存了模型。通过冻结mobilenet imagenet模型的最后一层进行培训。 加载模型并尝试预测会出错,说明ValueError:您试图将包含58层的权重文件加载到包含55层的模型中。 培训代码: # coding: utf-8 # In[1]: import pandas as pd import numpy as np import os import keras import matplotlib.pyplot as plt from keras.

我训练了我的模型,并以.h5格式保存了模型。通过冻结mobilenet imagenet模型的最后一层进行培训。 加载模型并尝试预测会出错,说明ValueError:您试图将包含58层的权重文件加载到包含55层的模型中。

培训代码:

# coding: utf-8

# In[1]:


import pandas as pd
import numpy as np
import os
import keras
import matplotlib.pyplot as plt
from keras.layers import Dense,GlobalAveragePooling2D
from keras.applications import MobileNet
from keras.preprocessing import image
from keras.applications.mobilenet import preprocess_input
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.optimizers import Adam

# In[2]:


base_model=MobileNet(weights='imagenet',include_top=False) #imports the mobilenet model and discards the last 1000 neuron layer.

x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(2,activation='softmax')(x) #final layer with softmax activation


# In[3]:


model=Model(inputs=base_model.input,outputs=preds)
#specify the inputs
#specify the outputs
#now a model has been created based on our architecture


# In[4]:


for layer in model.layers[:20]:
    layer.trainable=False
for layer in model.layers[20:]:
    layer.trainable=True


# In[5]:


train_datagen=ImageDataGenerator(preprocessing_function=preprocess_input) #included in our dependencies

train_generator=train_datagen.flow_from_directory('./train/', # this is where you specify the path to the main data folder
                                                 target_size=(224,224),
                                                 color_mode='rgb',
                                                 batch_size=64,
                                                 class_mode='categorical',
                                                 shuffle=True)


# In[33]:


model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
# Adam optimizer
# loss function will be categorical cross entropy
# evaluation metric will be accuracy

step_size_train=train_generator.n//train_generator.batch_size
model.fit_generator(generator=train_generator,
                   steps_per_epoch=step_size_train,
                   epochs=10)

# serialize model to JSON
model_json = model.to_json()
with open("mobilenet_2.json", "w") as json_file:
    json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("mobilenet_2.h5")
print("Saved model to disk")
预处理代码:

import keras
from keras import backend as K
from keras.layers.core import Dense, Activation
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
from keras.models import Model
from keras.applications import imagenet_utils
from keras.layers import Dense,GlobalAveragePooling2D
from keras.applications import MobileNet
from keras.applications.mobilenet import preprocess_input
import numpy as np
from keras.optimizers import Adam
from keras.models import load_model

model = load_model("mobilenet_1.h5")
#mobile = keras.applications.mobilenet.MobileNet(weights="imagenet")
def prepare_image(file):
    img_path = ''
    img = image.load_img("/home/christie/mobilenet/transfer-learning/" + file, target_size=(224, 224))
    img_array = image.img_to_array(img)
    img_array_expanded_dims = np.expand_dims(img_array, axis=0)
    return keras.applications.mobilenet.preprocess_input(img_array_expanded_dims)
'''
lookup_list = ["banana","banana_palenkodan","banana_red","banana_nendran","banana_karpooravalli"]
        #print(lookup_list)

    if ans not in lookup_list:sx
        print("Not found")
        return "[None]"
'''

preprocessed_image = prepare_image('test.jpg')
predictions = model.predict(preprocessed_image)
results = imagenet_utils.decode_predictions(predictions)
print(results)
错误日志:

ValueError:您正在尝试加载包含58层的权重文件 一个55层的模型


该模型转换为JSON格式,并写入本地目录中的mobilenet_2.JSON。网络权重写入本地目录中的mobilenet_2.h5

类似地,您必须加载json及其相应的权重

尝试按以下方式编辑:

# serialize model to JSON
model_json = model.to_json()
with open("mobilenet_2.json", "w") as json_file:
    json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("mobilenet_2.h5")
print("Saved model to disk")

# later...

# load json and create model
json_file = open('mobilenet_2.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("mobilenet_2.h5")
print("Loaded model from disk")
您只保存权重,但尝试加载模型架构和权重。如果要同时保存权重和模型体系结构并在以后加载,请尝试以下代码-

# save model and architecture to single file
model.save("model.h5")

# later...

# load model
model = load_model('model.h5')

@赛·克里希纳达斯——如果我已经回答了你的问题,你能接受并投票表决这个答案吗。非常感谢。