如何在 Keras 中将顺序模型添加到预训练模型中?

How do I prepend a sequential model to a pretrained model in Keras?

我想在像 nasnet_mobile 这样的预训练模型前面放置一个 4 层密集网络。我已经尝试了几种不同的方法,但它们都让人头疼(也就是错误)。在 keras+tensorflow2 中有什么方法可以做到这一点?

想法:

代码:

#LIBRARIES
import numpy as np
from tensorflow import keras
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Reshape, Conv2D, MaxPool2D , Flatten, Input


my_input_shape = (224,224,3)

#DENSE MODEL
my_inputs = Input(shape=my_input_shape)

hidden_1 = Dense(units=8, activation='relu')(my_inputs)


#make the output layer
hidden_2= Dense(units=np.product(my_input_shape), 
                           activation='sigmoid')(hidden_1)

transformed = keras.layers.Reshape(my_input_shape,)(hidden_2)  

dense_model = Model(inputs=my_inputs, outputs=transformed)

#PRETRAINED MODEL
pretrained_model = keras.applications.nasnet.NASNetMobile(weights = 'imagenet', 
                                                            include_top = False,
                                                            input_shape=my_input_shape)

#Option 1
combined_model_1 = keras.applications.nasnet.NASNetMobile(weights = 'imagenet', 
                                                            include_top = False,
                                                            input_tensor=transformed)

#Option 2
combined_model_2 = Model(inputs=dense_model.input, outputs=pretrained_model.output)

#Option 3a
combined_model_3a = keras.applications.nasnet.NASNetMobile(weights = 'imagenet', 
                                                            include_top = False,
                                                            input_tensor=my_input_shape)(dense_model)
#Option 3b
combined_model_3b = keras.applications.nasnet.NASNetMobile(weights = 'imagenet', 
                                                            include_top = False)(dense_model)

#Option 4
combined_model_4 = keras.applications.nasnet.NASNetMobile(weights = 'imagenet', 
                                                            include_top = False,
                                                            input_tensor=dense_model)

问题:
鉴于上述代码,我想在预训练模型前面菊花链连接 Dense 模型。我想将图像输入密集,让它通过密集传播,然后作为预训练的输入,并通过预训练。

为什么不这样做:

inp = Input(shape=my_input_shape)
x = dense_model(inp)
x = pretrained_model(x)

final_model = Model(inp, x)