如何在使用Tensorflow的传输学习中的模型之前添加几层

时间:2019-05-29 22:14:16

标签: tensorflow keras tf.keras transfer-learning mobilenet

我正在尝试在张量流中使用转移学习。我知道高级范例

base_model=MobileNet(weights='imagenet',include_top=False) #imports the 

mobilenet model and discards the last 1000 neuron layer.

x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(120,activation='softmax')(x) #final layer with softmax activation

然后由它编译

model=Model(inputs=base_model.input,outputs=preds)

但是我希望在base_model.input之前还有其他几层。我想给进来的图像和其他一些东西增加对抗性的噪音。如此有效,我想知道如何:

base_model=MobileNet(weights='imagenet',include_top=False) #imports the 

mobilenet model and discards the last 1000 neuron layer

x = somerandomelayers(x_in)
base_model.input = x_in
x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(120,activation='softmax')(x) #final layer with softmax activation
model=Model(inputs=x_in,outputs=preds)

但是行base_model.input = x_in显然不是这样做的方法,因为它会引发can't set attribute错误。我该如何实现所需的行为?

1 个答案:

答案 0 :(得分:1)

您需要定义输入层。这非常简单,只需确保设置正确的形状即可。例如,您可以使用Keras中的任何预定义模型。

base_model = keras.applications.any_model(...)
input_layer = keras.layers.Input(shape)
x = keras.layers.Layer(...)(input_layer)
...
x = base_model(x)
...
output = layers.Dense(num_classes, activation)(x)
model = keras.Model(inputs=input_layer, outputs=output)