【问题标题】:How to add a few layers before the model in transfer learning with tensorflow如何在使用 tensorflow 进行迁移学习的模型前添加几层
【发布时间】:2019-10-15 13:51:11
【问题描述】:

我正在尝试在 tensorflow 中使用迁移学习。我知道高级范式

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 错误。我该如何实现期望的行为?

【问题讨论】:

  • 你如何定义x_in?你想连接两个输入还是只在模型之前添加层?
  • 只需在模型前添加层。基本上我希望我的架构是。 layer1, layer2 ... layern --> modelinput-->modeloutput-->layerk,layersk+1 ...

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


【解决方案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)

【讨论】:

    猜你喜欢
    • 2016-05-07
    • 2020-08-06
    • 2016-05-18
    • 1970-01-01
    • 2017-05-13
    • 2020-01-14
    • 2022-11-27
    • 2023-03-27
    • 2018-04-12
    相关资源
    最近更新 更多