一般有两种方法可以实现:
快捷方式-支持的功能:
要改变最后一层的激活函数,你可以传递一个参数classifier_activation。
因此,为了一起摆脱激活,您的模块可以这样调用:
import tensorflow as tf
resnet = tf.keras.Sequential([
tf.keras.layers.Input(shape=(224,224,3)),
tf.keras.applications.ResNet50(
weights='imagenet',
input_shape=(224,224,3),
pooling="avg",
classifier_activation=None
)
])
但是,如果您想要不同的功能,这将不起作用,而 Keras classifer_activation 参数不支持(例如自定义激活功能)。
要实现这一点,您可以使用变通解决方案:
Long way - 复制模型的权重
此解决方案建议将原始模型的权重复制到您的自定义模型上。这种方法之所以有效,是因为除了激活函数之外,您并没有改变模型的架构。
您需要:
1.下载原始模型。
2. 保存它的权重。
3. 声明模型的修改版本(在您的情况下,没有激活函数)。
4. 设置新模型的权重。
下面的 sn-p 更详细地解释了这个概念:
import tensorflow as tf
# 1. Download original resnet
resnet = tf.keras.Sequential([
tf.keras.layers.Input(shape=(224,224,3)),
tf.keras.applications.ResNet50(
weights='imagenet',
input_shape=(224,224,3),
pooling="avg"
)
])
# 2. Hold weights in memory:
imagenet_weights = resnet.get_weights()
# 3. Declare the model, but without softmax
resnet_no_softmax = tf.keras.Sequential([
tf.keras.layers.Input(shape=(224,224,3)),
tf.keras.applications.ResNet50(
include_top=False,
weights='imagenet',
input_shape=(224,224,3),
pooling="avg"
),
tf.keras.layers.Dense(1000, name='fc1000')
])
# 4. Pass the imagenet weights onto the second resnet
resnet_no_softmax.set_weights(imagenet_weights)
希望这会有所帮助!