我正在尝试使用Keras微调一个模型:
inception_model = InceptionV3(weights=None, include_top=False, input_shape=(150, 150, 1)) x = inception_model.output x = GlobalAveragePooling2D()(x) x = Dense(256, activation='relu', name='fc1')(x) x = Dropout(0.5)(x) predictions = Dense(10, activation='softmax', name='predictions')(x) classifier = Model(inception_model.input, predictions) ####训练训练训练 ... 保存权重 classifier.load_weights("saved_weights.h5") classifier.layers.pop() classifier.layers.pop() classifier.layers.pop() classifier.layers.pop() ###足够的pop操作以恢复到标准的InceptionV3 x = classifier.output x = GlobalAveragePooling2D()(x) x = Dense(256, activation='relu', name='fc1')(x) x = Dropout(0.5)(x) predictions = Dense(10, activation='softmax', name='predictions')(x) classifier = Model(classifier.input, predictions)
但我遇到了以下错误:
ValueError: Input 0 is incompatible with layer global_average_pooling2d_3: expected ndim=4, found ndim=2
回答:
你不应该在使用函数式API创建的模型(即keras.models.Model
)上使用pop()
方法。只有Sequential模型(即keras.models.Sequential
)内置了pop()
方法(用法:model.pop()
)。相反,应该使用层的索引或名称来访问特定的层:
classifier.load_weights("saved_weights.h5")x = classifier.layers[-5].output # 直接使用层的索引x = GlobalAveragePooling2D()(x)