我有一个简单的CNN模型,如下所示:
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 26, 26, 32) 320
_________________________________________________________________
conv2d_2 (Conv2D) (None, 24, 24, 64) 18496
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 12, 12, 64) 0
_________________________________________________________________
dropout_1 (Dropout) (None, 12, 12, 64) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 9216) 0
_________________________________________________________________
dense_1 (Dense) (None, 128) 1179776
_________________________________________________________________
dropout_2 (Dropout) (None, 128) 0
_________________________________________________________________
dense_2 (Dense) (None, 10) 1290
=================================================================
Total params: 1,199,882.0
Trainable params: 1,199,882.0
Non-trainable params: 0.0
_________________________________________________________________
我已经弹出了dense_2(softmax图层)和dropout_2图层来从图像中提取特征:
(我正在使用这里提出的自定义弹出功能:https://github.com/fchollet/keras/issues/2640)
def pop_layer(model):
if not model.outputs:
raise Exception('Sequential model cannot be popped: model is empty.')
model.layers.pop()
if not model.layers:
model.outputs = []
model.inbound_nodes = []
model.outbound_nodes = []
else:
model.layers[-1].outbound_nodes = []
model.outputs = [model.layers[-1].output]
model.built = False
弹出最后两层:
pop_layer(model)
pop_layer(model)
之后执行model.summary()
:
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 26, 26, 32) 320
_________________________________________________________________
conv2d_2 (Conv2D) (None, 24, 24, 64) 18496
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 12, 12, 64) 0
_________________________________________________________________
dropout_1 (Dropout) (None, 12, 12, 64) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 9216) 0
_________________________________________________________________
dense_1 (Dense) (None, 128) 1179776
=================================================================
Total params: 1,198,592.0
Trainable params: 1,198,592.0
Non-trainable params: 0.0
_________________________________________________________________
最后两个图层是从模型中弹出的,但是当我正在做预测时:
predictions = model.predict(x_test)
print(len(predictions[0]))
10
正如你所看到的那样输出仍然是softmax,我做错了什么?
谢谢!
答案 0 :(得分:1)
事实证明,在build
图层之后,您需要compile
或pop
模型才能使模型正常运行。