在RESNET50中添加图层以建立JOIN CNN模型

时间:2019-12-27 12:12:11

标签: python tensorflow keras deep-learning resnet

这是我的代码,以便将resnet50模型与此模型(我想在我的数据集上进行训练)结合在一起。我想在代码中冻结resnet50模型的各层(请参见Trainable = false)。 在这里,我要导入resnet 50模型

`` 
import tensorflow.keras
import tensorflow as tf
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
resnet50_imagnet_model = tensorflow.keras.applications.resnet.ResNet50(weights = "imagenet", 
                           include_top=False, 
                           input_shape = (150, 150, 3),
                           pooling='max')
  ``

在这里我创建我的模型

 ```
# freeze feature layers and rebuild model
for l in resnet50_imagnet_model.layers:
    l.trainable = False

#construction du model
model5 = [
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(12, activation='softmax')
]

#Jointure des deux modeles
model_using_pre_trained_resnet50 = tf.keras.Sequential(resnet50_imagnet_model.layers + model5 )
 ```

最后一行不起作用,并且出现此错误: 层conv2_block1_3_conv的输入0与该层不兼容:输入形状的预期轴-1的值为64,但接收到形状为[无,38、38、256的输入

感谢帮助。

1 个答案:

答案 0 :(得分:2)

您也可以像下面一样使用keras的functional API

    from tensorflow.keras.applications.resnet50 import ResNet50
    import tensorflow as tf

    resnet50_imagenet_model = ResNet50(include_top=False, weights='imagenet', input_shape=(150, 150, 3))

    #Flatten output layer of Resnet
    flattened = tf.keras.layers.Flatten()(resnet50_imagenet_model.output)

    #Fully connected layer 1
    fc1 = tf.keras.layers.Dense(128, activation='relu', name="AddedDense1")(flattened)

    #Fully connected layer, output layer
    fc2 = tf.keras.layers.Dense(12, activation='softmax', name="AddedDense2")(fc1)

    model = tf.keras.models.Model(inputs=resnet50_imagenet_model.input, outputs=fc2)

另请参阅this question