我让模型使用以下代码:
def get_model(self, class_names, model_name="VGG16", use_base_weights=True,
weights_path=None, input_shape=None, model_id='global'):
if use_base_weights is True:
base_weights = "imagenet"
else:
base_weights = None
base_model_class = getattr(
importlib.import_module(
"keras.applications."+self.models_[model_name]['module_name']
),
model_name)
if input_shape is None:
input_shape = self.models_[model_name]["input_shape"]
img_input = Input(shape=input_shape)
base_model = base_model_class(
include_top=False,
input_tensor=img_input,
input_shape=input_shape,
weights=base_weights,
pooling="avg")
layer_dict = dict([(layer.name, layer) for layer in base_model.layers])
conv_outputs = None #last conv output
if model_name=="VGG16":
final_conv_layer = layer_dict["block5_conv3"]
conv_outputs = final_conv_layer.output
x = conv_outputs
loc = Get_heatmap(name='loc1')(conv_outputs)#x)
loc = keras.layers.UpSampling2D(2,name='loc')(loc)
num_maps=8
classes=11
x = WildcatPool2d(name='wildpool')(x)
predictions = Dense(len(class_names), activation="softmax", name="cls_pred")(x)
for layer in model.layers:
layer.name = layer.name + '_'+model_id
model.name=model_id+'_net'
if weights_path == "":
weights_path = None
if weights_path is not None:
print ("load model weights_path: {}".format(weights_path))
model.load_weights(weights_path, by_name=True)
return model
然后我将模型定义序列化为json并使用以下代码加载它:
optimizer = Adam(lr=initial_learning_rate)
model_train.compile(optimizer=optimizer, loss={
"cls_pred":"categorical_crossentropy",
"loc":mask_binary_crossentropy
},
loss_weights={'cls_pred': 1.,
'loc': 0.1
},
metrics={
"cls_pred":'accuracy',
"loc":mean_iou
}
)
model_json = model.to_json()
with open(model_id+"_model.json", "w") as json_file:
json_file.write(model_json)
from keras.models import model_from_json
json_file = open('gmodel.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
with CustomObjectScope({'WildcatPool2d': WildcatPool2d(),'Get_heatmap':Get_heatmap(),'mask_binary_crossentropy':mask_binary_crossentropy,'mean_iou':mean_iou}):
#model1=load_model('model.h5')#error,You are trying to load a weight file containing 14 layers into a model with 0 layers.
model1 = model_from_json(loaded_model_json)
#model1.load_weights('weights.h5')#error,You are trying to load a weight file containing 14 layers into a model with 0 layers.
print(model1.summary())
但是模型加载失败,当我加载权重时,错误是您正在尝试将包含14层的权重文件加载到0层的模型中,我打印了从json反序列化的模型,输出为yhis model print 我还检查了json文件,发现所有inbound_nodes都是空的,即使输出层和输入层也是空的(最后一张图片),所以模型没有放在一起。 我发现其他人遇到了问题,但没有找到一个好的解决方案。 json data part1