增加图像分类器中的类数

时间:2018-05-15 14:05:12

标签: python-3.x keras convolutional-neural-network

我在keras中使用CNN对两个对象(即狗和猫)的图像分类进行了编程。现在我怎样才能增加班级的数量,即狗,猫和青蛙?

以下是代码:

from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.callbacks import ModelCheckpoint

classifier = Sequential()

classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

classifier.add(Conv2D(32, (3, 3),  activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

classifier.add(Flatten())

classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

filepath="weights-improvment-{epoch:02d}-{val_acc:.2f}.hdf5"
checpoint=ModelCheckpoint(filepath,monitor='val_acc',verbose=1,save_best_only=True,mode='max')
callback_list=[checpoint]

from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('training_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
test_set = test_datagen.flow_from_directory('test_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
classifier.fit_generator(training_set, 
steps_per_epoch = 8000,
epochs = 10,
validation_data = test_set,
validation_steps = 2000)

classifier.save('model_after_trained.h5')

1 个答案:

答案 0 :(得分:1)

为了对两个以上的类进行分类,必须将最后一层中的神经元(单位)数量更改为要预测的类数。

假设您要预测3个对象,则必须将最后一个图层更改为: classifier.add(Dense(units = 3, activation = 'sigmoid'))

请找到以下链接,它将帮助您使用CNN进行多级分类:https://www.codesofinterest.com/2017/08/bottleneck-features-multi-class-classification-keras.html

希望这有帮助!!!