python - 获得固定精度:在使用 Google Colab 的 Keras 模型中为 0.5000,有时为 0.0000e+00
问题描述
我正在使用 Google Colab 上的 Keras 训练 CNN 模型进行二值图像分类,问题是当我使用 Sigmoid 函数时,我的准确度固定在 0.5000,当我将指标更改为“acc”时,我得到的准确度为 0.000e+00。此外,当我将激活函数更改为“Softmax”时,我的模型开始学习。
Ps:我正在使用 google colab,其中 Tensorflow 版本为 2.5.0
我的代码:
def define_model(input_shape, num_classes):
model=ResNet50(include_top = False, weights = 'imagenet', input_shape = input_shape)
x = model.output
x = GlobalAveragePooling2D()(x)
preds = Dense(num_classes,activation='sigmoid')(x)
model = Model(inputs=model.input,outputs=preds)
return model
def train(epochs):
train_generator = ImageDataGenerator(rescale=1.0/255.0,vertical_flip=True, horizontal_flip=True)
test_generator = ImageDataGenerator(rescale=1.0/255.0)
train_generator = train_generator.flow_from_directory(
'trainset/',
target_size=(image_size, image_size),
batch_size=BATCH_SIZE_TRAINING,
seed = 7)
validation_generator = test_generator.flow_from_directory(
'testset/',
target_size=(image_size, image_size),
batch_size=BATCH_SIZE_VALIDATION,
seed = 7)
input_shape = (CHANNELS, image_size, image_size) if K.image_data_format() == 'channels_first' \
else (image_size, image_size, CHANNELS)
model = define_model(input_shape, NUM_CLASSES)
opt = optimizers.Adam(learning_rate=1e-6, beta_1=0.9, beta_2=0.99, amsgrad=False)
model.summary()
model.compile(loss='binary_crossentropy',
optimizer=opt,
metrics=['acc'])
filepath=path+"weights-improvement-{epoch:02d}-vacc:{val_accuracy:.2f}-tacc:{accuracy:.2f}.hdf5"
'''cb_early_stopper = EarlyStopping(monitor = 'val_accuracy', mode='min', verbose=1, patience = EARLY_STOP_PATIENCE)
cb_checkpointer = ModelCheckpoint(filepath = filepath, monitor = 'val_accuracy', save_best_only = True, mode = 'auto')
reduce_lr = ReduceLROnPlateau(monitor='val_accuracy', factor=0.25, patience=5, min_lr=1e-7)'''
fit_history = model.fit(train_generator,
epochs = NUM_EPOCHS,
validation_data=validation_generator,
verbose=1,
class_weight=class_weights)
# callbacks = [cb_checkpointer, cb_early_stopper, reduce_lr],
return model, fit_history
def main():
start_time = time()
model, fit_history = train(epochs=NUM_EPOCHS)
end_time = time()
seconds_elapsed = end_time - start_time
print('token time: ', seconds_elapsed)
hours, rest = divmod(seconds_elapsed, 3600)
minutes, seconds = divmod(rest, 60)
if __name__ == "__main__":
main()
解决方案
通过将此代码添加到 .flow_from_directory() 函数解决的问题:
class_mode='binary',
感谢 github 上的这个帖子: https ://github.com/keras-team/keras/issues/13006
推荐阅读
- vba - 为什么重复 VBA 公式 R1C1 按行偏移引用?
- vba - 如何实现灵活的对象组合?
- javascript - 如何优化计算代码行数的算法?
- css - 使用 Gulp 根据媒体查询将 SASS/CSS 文件拆分为多个 CSS 文件?
- r - 在 R 中,为日期分配一个数字,其中该数字对应于该日期包含在一年中的第 n 个滚动、非重叠时期
- java - 如何在 Junit5 中测试方法
- javascript - 没有默认按钮的电报授权
- python - 为什么这个 python selenium 示例不起作用?
- ansible - Ansible playbook - NPM 任务未并行运行
- pdf - GhostScript PDF to PCL 黑白无灰度