是否可以在Keras/TensorFlow中提取多输入模型的一部分



我有这个多输入网络:

def build_model():
inputRGB = tf.keras.Input(shape=(128,128,3), name='train_ds')
inputFixed = tf.keras.Input(shape=(128,128,3), name='fixed_ds')
inputDinamic = tf.keras.Input(shape=(128,128,3), name='dinamic_ds')
# rete per Immagini RGB
rgb = models.Sequential()  
rgb = layers.Conv2D(32, (5, 5), padding='SAME')(inputRGB)
rgb = layers.PReLU()(rgb)
rgb = layers.MaxPooling2D((2, 2))(rgb)
rgb = layers.BatchNormalization()(rgb)
rgb = layers.Conv2D(64, (3, 3))(rgb)
rgb = layers.PReLU()(rgb)
rgb = layers.Conv2D(64, (3, 3))(rgb)
rgb = layers.PReLU()(rgb)
rgb = layers.Conv2D(64, (3, 3))(rgb)
rgb = layers.PReLU()(rgb)
rgb = layers.Dropout(0.5)(rgb)
rgb = layers.GlobalAvgPool2D()(rgb)
rgb = Model(inputs = inputRGB, outputs=rgb)
# rete per Density Map con "Pallini"
fixed = models.Sequential()
fixed = layers.Conv2D(32, (5, 5), padding='SAME')(inputFixed)
fixed = layers.PReLU()(fixed)
fixed = layers.MaxPooling2D((2, 2))(fixed)
fixed = layers.BatchNormalization()(fixed)
fixed = layers.Conv2D(64, (3, 3))(fixed)
fixed = layers.PReLU()(fixed)
fixed = layers.Conv2D(64, (3, 3))(fixed)
fixed = layers.PReLU()(fixed)
fixed = layers.Conv2D(64, (3, 3))(fixed)
fixed = layers.PReLU()(fixed)
fixed = layers.Dropout(0.5)(fixed)
fixed = layers.GlobalAvgPool2D()(fixed)
fixed = Model(inputs = inputFixed, outputs=fixed)
# rete per Density map per "assembramenti"
dinamic = models.Sequential()  
dinamic = layers.Conv2D(32, (5, 5), padding='SAME')(inputDinamic)
dinamic = layers.PReLU()(dinamic)
dinamic = layers.MaxPooling2D((2, 2))(dinamic)
dinamic = layers.BatchNormalization()(dinamic)
dinamic = layers.Conv2D(64, (3, 3))(dinamic)
dinamic = layers.PReLU()(dinamic)
dinamic = layers.Conv2D(64, (3, 3))(dinamic)
dinamic = layers.PReLU()(dinamic)
dinamic = layers.Conv2D(64, (3, 3))(dinamic)
dinamic = layers.PReLU()(dinamic)
dinamic = layers.Dropout(0.5)(dinamic)
dinamic = layers.GlobalAvgPool2D()(dinamic)
dinamic = Model(inputs = inputDinamic, outputs=dinamic)
concat = layers.concatenate([rgb.output, fixed.output, dinamic.output])  # merge the outputs of the two models
k = layers.Dense(1)(concat)
modelFinal = Model(inputs={'train_ds':inputRGB, 'fixed_ds':inputFixed, 'dinamic_ds':inputDinamic}, outputs=[k])
opt = tf.keras.optimizers.Adam(learning_rate=0.001, amsgrad=False)

modelFinal.compile(optimizer=opt , loss='mae', metrics=['mae'])
return modelFinal

我想从我保存并重新加载的最佳模型中提取以下代码行:

best_model = tf.keras.models.load_model(checkpoint_path + 'regression_count_128.30-1.11.hdf5')

只是前面显示的多输入神经网络的第一部分。具体来说,我想提取将RGB图像作为输入的部分,以便仅在RGB测试图像上测试模型(用3种不同类型的图像训练(。

使用RGB部分的输入层名称(即'train_ds'(和输出层名称(您尚未命名,但可以使用best_model.summary()找到它;它从'global_average_pooling2d'开始(来构建这样的新模型:

rgb_model = Model(
best_model.get_layer('train_ds').output,
best_model.get_layer(name_of_rgb_output_layer).output
)

旁注:... = model.Sequential()行是多余的,可以删除,因为您正在使用keras的功能性API来定义您的模型。

相关内容

最新更新