【发布时间】:2017-08-19 05:38:05
【问题描述】:
我有一个带有relu 激活的普通 VGG16 模型,即
def VGG_16(weights_path=None):
model = Sequential()
model.add(ZeroPadding2D((1, 1),input_shape=(3, 224, 224)))
model.add(Convolution2D(64, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(64, 3, 3, activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
[...]
model.add(Flatten())
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1000, activation='softmax'))
if weights_path:
model.load_weights(weights_path)
return model
我正在使用现有权重对其进行实例化,现在想将所有 relu 激活更改为 softmax(我知道这没什么用)
model = VGG_16('vgg16_weights.h5')
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
softmax_act = keras.activations.softmax
for (n, layer) in enumerate(model.layers):
if 'activation' in layer.get_config() and layer.get_config()['activation'] == 'relu':
print('replacing #{}: {}, {}'.format(n, layer, layer.activation))
layer.activation = softmax_act
print('-> {}'.format(layer.activation))
model.compile(optimizer=sgd, loss='categorical_crossentropy')
注意:model.compile 在更改之后被称为,所以我猜模型应该仍然可以修改。
但是,即使调试打印正确地说
replacing #1: <keras.layers.convolutional.Convolution2D object at 0x7f7d7c497f50>, <function relu at 0x7f7dbe699a28>
-> <function softmax at 0x7f7d7c4972d0>
[...]
实际结果与具有relu 激活的模型相同。
为什么 Keras 不使用更改后的激活函数?
【问题讨论】:
标签: python keras keras-layer