我正试图在Keras中对预先训练好的Inceptionv3进行微调,以解决多标签(17)预测问题。
以下是代码:
# create the base pre-trained model
base_model = InceptionV3(weights='imagenet', include_top=False)
# add a new top layer
x = base_model.output
predictions = Dense(17, activation='sigmoid')(x)
# this is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)
# we need to recompile the model for these modifications to take effect
# we use SGD with a low learning rate
from keras.optimizers import SGD
model.compile(loss='binary_crossentropy', # We NEED binary here, since categorical_crossentropy l1 norms the output before calculating loss.
optimizer=SGD(lr=0.0001, momentum=0.9))
# Fit the model (Add history so that the history may be saved)
history = model.fit(x_train, y_train,
batch_size=128,
epochs=1,
verbose=1,
callbacks=callbacks_list,
validation_data=(x_valid, y_valid))
但是我遇到了以下错误消息,并且无法破译它所说的内容:
ValueError:检查目标时出错:期望dense_1有4 尺寸,但得到形状的数组(1024,17)
它似乎与某些事情有关,它不喜欢我作为目标的标签的单热编码。但是如何获得4个维度?
答案 0 :(得分:1)
事实证明,从https://keras.io/applications/复制的代码不会是开箱即用的。 以下帖子帮助了我: Keras VGG16 fine tuning
我需要做出的改变如下:
将输入形状添加到模型定义base_model = InceptionV3(weights='imagenet', include_top=False, input_shape=(299,299,3))
和
添加Flatten()图层以展平张量输出:
x = base_model.output
x = Flatten()(x)
predictions = Dense(17, activation='sigmoid')(x)
然后该模型适合我!