【问题标题】:image classifer with multiple categories具有多个类别的图像分类器
【发布时间】:2019-12-06 14:23:23
【问题描述】:

嗨,我遵循了关于如何从这里https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html 制作图像分类器的指南,并将其分类为仅 2 个类别,这些代码给了我 F1 分数和混淆矩阵有没有办法使用制作多类别图像分类器这些代码我现在的数据集是蘑菇的类型

import numpy
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
import matplotlib.pyplot as plt


# dimensions of our images.
img_width, img_height = 150, 150

train_data_dir = r'C:\Users\Acer\imagerec\Mushrooms\TRAIN'
validation_data_dir = r'C:\Users\Acer\imagerec\Mushrooms\VAL'
nb_train_samples = 7025
nb_validation_samples = 6262
epochs = 50
batch_size = 16

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

model.save_weights('first_try.h5')

from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
import seaborn as sns

test_steps_per_epoch = numpy.math.ceil(validation_generator.samples / validation_generator.batch_size)

predictions = model.predict_generator(validation_generator, steps=test_steps_per_epoch)
# Get most likely class
predicted_classes = numpy.argmax(predictions, axis=1)
true_classes = validation_generator.classes
class_labels = list(validation_generator.class_indices.keys())
report = classification_report(true_classes, predicted_classes, target_names=class_labels)
print(report)

cm=confusion_matrix(true_classes,predicted_classes)

sns.heatmap(cm, annot=True)

print(cm)

plt.show()

【问题讨论】:

    标签: python machine-learning


    【解决方案1】:

    您在代码中明确定义了二进制分类。要将其转换为多类任务,例如 N 类,您需要将最后一层从1 Dense 更改为N Dense,并且为了激活,您应该将其更改为@ 987654323@ 至softmax。 最后但同样重要的是,如果您的类已经是热编码的,您应该将损失函数从 binary_crossentropy 更改为 categorical_crossentropy。否则,您可能想要使用 sparse_categorical_crossentropy

    应用更改后,您的那部分代码应该看起来像这样:

    model.add(Dense(N))
    model.add(Activation('softmax'))
    
    model.compile(loss='categorical_crossentropy',
                      optimizer='rmsprop',
                      metrics=['accuracy'])
    

    其中 N 是您拥有的不同类别的数量。

    编辑:您还需要将生成器中的 class_mode 从“二进制”转换为“分类”。您还应该检查如何生成标签(单热编码)

    【讨论】:

      猜你喜欢
      • 2012-11-10
      • 2019-01-10
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多