我训练了一个有4个隐藏层和2个密集层的模型,我保存了那个模型。
现在我想要加载该模型,并希望分成两个模型,一个有一个隐藏层,另一个只有密集层。
我已按以下方式将模型与隐藏图层分开
model = load_model ("model.hdf5")
HL_model = Model(inputs=model.input, outputs=model.layers[7].output)
这里模型是加载模型,在第7层是我的最后一个隐藏层。我试图将密集分裂成类似的
DL_model = Model(inputs=model.layers[8].input, outputs=model.layers[-1].output)
我收到错误
TypeError: Input layers to a `Model` must be `InputLayer` objects.
分割后,HL_model的输出将是DL_model的输入。
任何人都可以帮我创建一个具有密集层的模型吗?
PS: 我也试过下面的代码
from keras.layers import Input
inputs = Input(shape=(9, 9, 32), tensor=model_1.layers[8].input)
model_3 = Model(inputs=inputs, outputs=model_1.layers[-1].output)
收到错误
RuntimeError: Graph disconnected: cannot obtain value for tensor Tensor("conv2d_1_input:0", shape=(?, 144, 144, 3), dtype=float32) at layer "conv2d_1_input". The following previous layers were accessed without issue: []
模型的输入图像尺寸(144,144,3)。
答案 0 :(得分:3)
您需要先指定一个新的Input
图层,然后将剩余的图层叠加在其上:
DL_input = Input(model.layers[8].input_shape[1:])
DL_model = DL_input
for layer in model.layers[8:]:
DL_model = layer(DL_model)
DL_model = Model(inputs=DL_input, outputs=DL_model)
答案 1 :(得分:0)
更通用一点。您可以使用以下函数来拆分模型
from keras.layers import Input
from keras.models import Model
def get_bottom_top_model(model, layer_name):
layer = model.get_layer(layer_name)
bottom_input = Input(model.input_shape[1:])
bottom_output = bottom_input
top_input = Input(layer.output_shape[1:])
top_output = top_input
bottom = True
for layer in model.layers:
if bottom:
bottom_output = layer(bottom_output)
else:
top_output = layer(top_output)
if layer.name == layer_name:
bottom = False
bottom_model = Model(bottom_input, bottom_output)
top_model = Model(top_input, top_output)
return bottom_model, top_model
bottom_model, top_model = get_bottom_top_model(model, "dense_1")
Layer_name 只是您要拆分的图层的名称。