首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ValueError:您正在尝试将包含58个层的权重文件加载到一个具有55个层的模型中。

ValueError:您正在尝试将包含58个层的权重文件加载到一个具有55个层的模型中。
EN

Stack Overflow用户
提问于 2020-03-05 06:34:12
回答 1查看 306关注 0票数 0

我训练了我的模型,并以.h5格式保存了模型。通过冻结移动集imagenet模型的最后一层进行培训。加载模型并尝试预测会导致错误,说明ValueError:您正在尝试将包含58个层的权重文件加载到具有55个层的模型中。

培训代码:

代码语言:javascript
复制
# 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")

预测码:

代码语言:javascript
复制
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层的模型中。

EN

回答 1

Stack Overflow用户

发布于 2020-03-05 09:11:29

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

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

试着按以下方式编辑:

代码语言:javascript
复制
# 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")

您只保存权重,但尝试加载模型体系结构和权重。如果您想将权重和模型体系结构一起保存并在以后加载,请尝试以下代码-

代码语言:javascript
复制
# save model and architecture to single file
model.save("model.h5")

# later...

# load model
model = load_model('model.h5')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60539431

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档