即使我用的MobileNetV2 预训练模型,发现执行以下操作:
base_model = MobileNetV2(weights=None, include_top=False, pooling=None, input_shape=(ROWS, COLS, CHANNELS), classes=2)
base_model.load_weights('/home/ma-user/work/weights trained on ImageNet/Keras/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_1.0_224_no_top.h5')
x = base_model.output
#添加自己的全链接分类层
x = Flatten()(x)
# x = Dense(1024, activation='relu')(x)# 这一层增加了太多参数
x = Dense(124, activation='relu')(x)# 这一层增加了太多参数
x = Dropout(0.4)(x)
predictions = Dense(2, activation='softmax')(x)
#训练模型
model = Model(inputs=base_model.input, outputs=predictions)
model.summary()
训练出来的模型 大小既然达到 1.07GB!!!
我预训练模型才 不到 10MB啊!
发现情况不对,赶紧查找办法。
首先,我马上想到,我只是去掉了头部,引入几层全连接层 改变了下模型,那么,
我引入 include_top=True 打印一下参数看看它最后几层结构。和我现在的区别
from keras.applications.mobilenet_v2 import MobileNetV2
base_model =MobileNetV2(include_top=True, weights=None, input_tensor=None, input_shape=None, pooling=None, classes=1000)
base_model.summary()
这是不含头部的 最后几层:
这是含头部的 最后几层:
这是我不含头部后面加了 Flatten,Dense和softmax的末尾结构:
x = Flatten()(x)
x = Dense(1024, activation='relu')(x)# 这一层增加了太多参数
x = Dropout(0.4)(x)
predictions = Dense(2, activation='softmax')(x)
明显看到,是因为引入 Flatten 和 Dense 1 导致的参数巨大。
那么,问题来了,后面去掉尾部,该怎么改,且保证性能不下降的情况下,模型依然鲁棒呢?