同时建立一个模型,其中包括转移学习(从VGG-16)。我遇到了这种奇怪的行为。Tensorboard图显示的不是新模型的一部分,而是旧模型的一部分,在分离点之上,它们只是悬在那里。

在进一步研究时,model.summary()没有显示这些层,model.get_layer("block4_conv1")也找不到它们,keras tf.keras.utils.plot_model也没有显示它们。但是如果它们不是图的一部分,张拉板怎么会知道它们呢?
为了建立新的模型,我使用了推荐的方法。
模型第一阶段:
vgg_input_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False, input_tensor=x)
final_vgg_kayer = vgg_input_model.get_layer("block3_pool")
input_model = tf.keras.Model(inputs=vgg_input_model.inputs, outputs=final_vgg_kayer.output)
input_model.trainable = True
x = tf.keras.layers.Conv2D(512, 1, padding="same", activation='relu', name="stage0_final_conv1")(input_model.output)
x = tf.keras.layers.Conv2D(512, 1, padding="same", activation='relu', name="stage0_final_conv2")(x)
x = tf.keras.layers.Conv2D(256, 1, padding="same", activation='relu', name="stage0_final_conv3")(x)
x = tf.keras.layers.Conv2D(128, 1, padding="same", activation='relu', name="stage0_final_conv4")(x)TF:2.1 (nightly-2.x)
PY:3.5
Tensorboard: 2.1.0a20191124发布于 2019-11-30 15:50:45
在尝试了多种方法之后,我得出了这样的结论:推荐的方法是错误的。执行model_b=tf.keras.Model(inputs=model_a.inputs,outputs=model_a.get_layet("some_layer").output)将导致从model_a中悬空的层。在中间使用tf.keras.backend.clear_session()可以清理角图,而张板图则是空的。
我找到的最佳解决方案是逐层复制所需模型的config+weights。在一个新的模型中重建连接。这样,两个模型之间在Keras图中就没有任何关系了。(对于VGG这样的顺序模型来说,这很简单,但是对于像ResNet这样的模型来说可能更难)
样本代码:
tf.keras.backend.clear_session()
input_shape = (368, 368, 3) #only the input shape is shared between the models
#transfer learning model definition
input_layer_vgg = tf.keras.layers.Input(shape=input_shape)
vgg_input_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False, input_tensor=input_layer_vgg)
name_last_layer = "block3_pool" #the last layer to copy
tf.keras.backend.clear_session() #clean the graph from the transfer learning model
input_layer = tf.keras.layers.Input(shape=input_shape) #define the input layer for the first model
x=input_layer
for layer in vgg_input_model.layers[1:]: #copy over layers, without the other input layer
config=layer.get_config() #get config
weights=layer.get_weights() #get weights
#print(config)
copy_layer=type(layer).from_config(config) #create the new layer from config
x=copy_layer(x) #connect to previous layers,
#required for the proper sizing of the layer,
#set_weights will not work without it
copy_layer.set_weights(weights)
if layer.name == name_last_layer:
break
del vgg_input_model
input_model=tf.keras.Model(inputs=input_layer,outputs=x) #create the new model,
#if needed x can be used further doen the linehttps://stackoverflow.com/questions/59105384
复制相似问题