我是深度学习和Keras
的新手。使用下面的简单训练代码,我对10个班进行了分类。但现在我想重用这个代码,并将这个代码转换为二进制情况,在这种情况下,我说图像是否是我的对象。
我尝试将激活从softmax
更改为sigmoid
,还更改了更新的loss='binary_crossentropy'
。这足以改变吗?还有其他变化吗?
我得到一个错误说:
File "train.py", line 94, in <module>
shuffle=True, callbacks=callbacks_list)
File "/usr/local/lib/python3.5/dist-packages/keras/legacy/interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 1732, in fit_generator
initial_epoch=initial_epoch)
File "/usr/local/lib/python3.5/dist-packages/keras/engine/training_generator.py", line 260, in fit_generator
callbacks.on_epoch_end(epoch, epoch_logs)
File "/usr/local/lib/python3.5/dist-packages/keras/callbacks/callbacks.py", line 152, in on_epoch_end
callback.on_epoch_end(epoch, logs)
File "/usr/local/lib/python3.5/dist-packages/keras/callbacks/callbacks.py", line 702, in on_epoch_end
filepath = self.filepath.format(epoch=epoch + 1, **logs)
KeyError: 'acc'
这是我用于多类分类的简单训练代码:
#==========================
HEIGHT = 300
WIDTH = 300
TRAIN_DIR = "data"
BATCH_SIZE = 8 #8
steps_per_epoch = 1000 #1000
NUM_EPOCHS = 50 #50
lr= 0.00001
#==========================
FC_LAYERS = [1024, 1024]
dropout = 0.5
def build_finetune_model(base_model, dropout, fc_layers, num_classes):
for layer in base_model.layers:
layer.trainable = False
x = base_model.output
x = Flatten()(x)
for fc in fc_layers:
# New FC layer, random init
x = Dense(fc, activation='relu')(x)
x = Dropout(dropout)(x)
# New softmax layer
predictions = Dense(num_classes, activation='softmax')(x)
finetune_model = Model(inputs=base_model.input, outputs=predictions)
return finetune_model
train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
train_generator = train_datagen.flow_from_directory(TRAIN_DIR,
target_size=(HEIGHT, WIDTH),
batch_size=BATCH_SIZE)
base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(HEIGHT, WIDTH, 3))
root=TRAIN_DIR
class_list = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ]
print (class_list)
FC_LAYERS = [1024, 1024]
dropout = 0.5
finetune_model = build_finetune_model(base_model, dropout=dropout, fc_layers=FC_LAYERS, num_classes=len(class_list))
adam = Adam(lr=0.00001)
finetune_model.compile(adam, loss='categorical_crossentropy', metrics=['accuracy'])
filepath="./checkpoints/" + "MobileNetV2_{epoch:02d}_{acc:.2f}" +"_model_weights.h5"
checkpoint = ModelCheckpoint(filepath, monitor=["acc"], verbose=1, mode='max', save_weights_only=True)
callbacks_list = [checkpoint]
history = finetune_model.fit_generator(train_generator, epochs=NUM_EPOCHS, workers=8,
steps_per_epoch=steps_per_epoch,
shuffle=True, callbacks=callbacks_list)
好吧,你应该只有一个输出节点,因为它将具有类的概率(因此1-这是没有该类的概率(。
将激活更改为sigmoid
是正确的,因为您希望使用条件类型的概率输出,而不是联接概率。
二进制交叉熵是正确的应用,因为你处理的是二进制目标数据。
最后,错误似乎是您在monitor
中传递的关键字。尝试将其替换为monitor= "val_accuracy"
。