gpt4 book ai didi

tensorflow - Keras 为什么二元分类不如分类分类准确

转载 作者:行者123 更新时间:2023-11-30 09:30:39 28 4
gpt4 key购买 nike

我正在尝试创建一个模型,可以判断图像中是否有鸟。

我使用分类分类来训练模型来识别 Bird 与 Bird。花儿,结果在识别这两个类方面非常成功。

但是,当我将其更改为二元分类来检测图像中是否存在鸟类时,准确性急剧下降。

The reason why I changed to use Binary classification is that if I provided a dog to my Categorical Classification trained model, it recognized the dog as a bird.

顺便说一句,这是我的数据集结构:

培训:5000 张鸟类图像和 2000 张非鸟类图像

验证:1000 张鸟类图像和 500 张非鸟类图像

enter image description here

有人说,数据不平衡也会带来问题。这是真的吗?

有人可以指出我在以下代码中出错的地方吗?

def get_num_files(path):
if not os.path.exists(path):
return 0
return sum([len(files) for r, d, files in os.walk(path)])

def get_num_subfolders(path):
if not os.path.exists(path):
return 0
return sum([len(d) for r, d, files in os.walk(path)])

def create_img_generator():
return ImageDataGenerator(
preprocessing_function=preprocess_input,
rotation_range=30,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
)

INIT_LT = 1e-3
Image_width, Image_height = 299, 299
Training_Epochs = 30
Batch_Size = 32
Number_FC_Neurons = 1024
Num_Classes = 2

train_dir = 'to my train folder'
validate_dir = 'to my validation folder'


num_train_samples = get_num_files(train_dir)
num_classes = get_num_subfolders(train_dir)
num_validate_samples = get_num_files(validate_dir)

num_epoch = Training_Epochs
batch_size = Batch_Size

train_image_gen = create_img_generator()
test_image_gen = create_img_generator()

train_generator = train_image_gen.flow_from_directory(
train_dir,
target_size=(Image_width, Image_height),
batch_size = batch_size,
seed = 42
)

validation_generator = test_image_gen.flow_from_directory(
validate_dir,
target_size=(Image_width, Image_height),
batch_size=batch_size,
seed=42
)

Inceptionv3_model = InceptionV3(weights='imagenet', include_top=False)
print('Inception v3 model without last FC loaded')

x = Inceptionv3_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(Number_FC_Neurons, activation='relu')(x)
predictions = Dense(num_classes, activation='softmax')(x)

# model = Model(inputs=Inceptionv3_model.input, outputs=predictions)
v3model = Model(inputs=Inceptionv3_model.input, outputs=predictions)
# Use new Sequential model to add v3model and add a bath normalization layer after
model = Sequential()
model.add(v3model)
model.add(BatchNormalization()) # added normalization
print(model.summary())

print('\nFine tuning existing model')

Layers_To_Freeze = 172
for layer in model.layers[:Layers_To_Freeze]:
layer.trainable = False
for layer in model.layers[Layers_To_Freeze:]:
layer.trainable = True

optizer = Adam(lr=INIT_LT, decay=INIT_LT / Training_Epochs)
# optizer = SGD(lr=0.0001, momentum=0.9)
model.compile(optimizer=optizer, loss='binary_crossentropy', metrics=['accuracy'])

cbk_early_stopping = EarlyStopping(monitor='val_acc', mode='max')

history_transfer_learning = model.fit_generator(
train_generator,
steps_per_epoch = num_train_samples,
epochs=num_epoch,
validation_data=validation_generator,
validation_steps = num_validate_samples,
class_weight='auto',
callbacks=[cbk_early_stopping]
)

model.save('incepv3_transfer_mini_binary.h5', overwrite=True, include_optimizer=True)

最佳答案

分类

  • 使用Num_Classes = 2
  • 使用单热编码目标(例如:Bird = [1, 0]Flower = [0, 1])
  • 使用'softmax'激活
  • 使用'categorical_crossentropy'

二进制

  • 使用Num_Classes = 1
  • 使用二进制目标(例如:是花 = 1 | 不是花 = 0)
  • 使用'sigmoid'激活
  • 使用'binary_crossentropy'

详细信息请参见:Using categorical_crossentropy for only two classes

关于tensorflow - Keras 为什么二元分类不如分类分类准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59410176/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com