tensorflow - 如何在使用 tensorflow 的迁移学习中在模型之前添加几层

标签 tensorflow keras tf.keras transfer-learning mobilenet

我正在尝试在 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 错误。我该如何实现预期的行为?

最佳答案

您需要定义输入层。这相当简单,只要确保设置正确的形状即可。例如,您可以使用 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)

关于tensorflow - 如何在使用 tensorflow 的迁移学习中在模型之前添加几层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56369228/

相关文章:

machine-learning - 如何重置 Keras 中的状态变量?

python - ValueError : Layer weight shape (3, 3, 3, 64) 与提供的权重形状 (64, 3, 3, 3) 不兼容

python - 属性错误 : 'Sequential' object has no attribute 'total_loss'

tensorflow - 我可以使用 TensorFlow 用新数据重新训练旧模型吗?

python - VS Code/Pylance/Pylint 无法解析导入

python - tf.nn.static_rnn - 输入必须是序列

python - session 和并行在 TF2.0 中如何工作?

tensorflow - 为不平衡数据加权回归CNN?

python - 如何在keras中连接不同的张量形状

python - 使用 keras 和 tensorflow 调整大小会产生不同的结果