我在CNN上使用二进制分类器。我有两个类别“我”和“其他”。我有大约250张自己的图像和500张其他图像(随机面部数据库)。我目前的图层实现非常简单
public class Vin {
@Expose
private String vin;
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
}
public class Vins {
@Expose
List<Vin> vins = new ArrayList<>();
public List<Vin> getVins() {
return vins;
}
public void addVins(Vin vin) {
this.vins.add(vin);
}
}
我的问题是,当我使用这个网络来预测面孔时,它总是将任何面部识别为我的面孔。我已经裁剪了面部,应用了gabor过滤器,但没有任何作用。任何建议将不胜感激。
随机面的预测结果:[KK代表我的脸] 概率总是超过97%:
self.model.add(Conv2D(128, (2, 2), padding='same',
input_shape=dataset.X_train.shape[1:]))
self.model.add(Activation('relu'))
self.model.add(MaxPooling2D(pool_size=(2, 2)))
self.model.add(Dropout(0.25))
self.model.add(Conv2D(64, (2, 2), padding='same'))
self.model.add(Activation('relu'))
self.model.add(MaxPooling2D(pool_size=(2, 2)))
self.model.add(Dropout(0.25))
self.model.add(Conv2D(32, (1, 1), padding='same'))
self.model.add(Activation('relu'))
self.model.add(MaxPooling2D(pool_size=(2, 2)))
self.model.add(Dropout(0.5))
self.model.add(Dense(512))
self.model.add(Activation('relu'))
self.model.add(Dropout(0.25))
self.model.add(Dense(2)) # for two classes
self.model.add(Activation('softmax'))
我的图像预测结果:[KK代表我的脸] 概率总是超过99%:
KK identified!
1/1 [==============================] - 0s
[[ 0.9741978 0.0258022]]
1/1 [==============================] - 0s
KK identified!
1/1 [==============================] - 0s
[[ 0.9897241 0.01027592]]
1/1 [==============================] - 0s
培训代码
KK identified!
1/1 [==============================] - 0s
[[ 0.99639165 0.00360837]]
1/1 [==============================] - 0s
KK identified!
1/1 [==============================] - 0s
[[ 0.99527925 0.00472075]]
1/1 [==============================] - 0s
由于
[更新:6月11日]
层
def get_data(self, img_rows=IMAGE_SIZE, img_cols=IMAGE_SIZE, img_channels=3, nb_classes=2):
images, labels = fetch_data('./data/')
labels = np.reshape(labels, [-1])
X_train, X_test, y_train, y_test = \
train_test_split(images, labels, test_size=0.3, random_state=random.randint(0, 100))
X_valid, X_test, y_valid, y_test = \
train_test_split(images, labels, test_size=0.3, random_state=random.randint(0, 100))
#train_test_split(images, labels, test_size=0.3, random_state=np.random.seed(15))
if K.image_dim_ordering() == 'th':
X_train = X_train.reshape(X_train.shape[0], 3, img_rows, img_cols)
X_valid = X_valid.reshape(X_valid.shape[0], 3, img_rows, img_cols)
X_test = X_test.reshape(X_test.shape[0], 3, img_rows, img_cols)
# input_shape = (3, img_rows, img_cols)
else:
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 3)
X_valid = X_valid.reshape(X_valid.shape[0], img_rows, img_cols, 3)
X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 3)
# input_shape = (img_rows, img_cols, 3)
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_valid = np_utils.to_categorical(y_valid, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
X_train = X_train.astype('float32')
X_valid = X_valid.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_valid /= 255
X_test /= 255
self.X_train = X_train
self.X_valid = X_valid
self.X_test = X_test
self.Y_train = Y_train
self.Y_valid = Y_valid
self.Y_test = Y_test
def train_network(self, dataset, batch_size=32, nb_epoch=40, data_augmentation=True):
sgd = SGD(lr=0.003, decay=0.0000001, momentum=0.9, nesterov=True)
# adam = Adam(lr=0.01, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0001)
self.model.compile(loss='binary_crossentropy',
optimizer=sgd,
metrics=['accuracy'])
if not data_augmentation:
processed_data = self.model.fit(dataset.X_train, dataset.Y_train,
batch_size=batch_size,
nb_epoch=nb_epoch,
validation_data=(dataset.X_valid, dataset.Y_valid),
shuffle=True)
else:
datagenerator = ImageDataGenerator(
featurewise_center=False,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True,
vertical_flip=False)
datagenerator.fit(dataset.X_train)
processed_data = self.model.fit_generator(datagen.flow(dataset.X_train, dataset.Y_train, batch_size=batch_size, shuffle=True),
samples_per_epoch=dataset.X_train.shape[0], nb_epoch=nb_epoch, validation_data=(dataset.X_valid, dataset.Y_valid))
数据扩充
def build_model(self, dataset, nb_classes=2):
self.model = Sequential()
self.model.add(Conv2D(32, (3, 3), padding='same', input_shape=dataset.X_train.shape[1:]))
self.model.add(Activation('relu'))
self.model.add(Conv2D(32, (3, 3)))
self.model.add(Activation('relu'))
self.model.add(MaxPooling2D(pool_size=(2, 2)))
self.model.add(Dropout(0.5))
self.model.add(Conv2D(16, (3, 3), padding='same'))
self.model.add(Activation('relu'))
self.model.add(Conv2D(16, (3, 3)))
self.model.add(Activation('relu'))
self.model.add(MaxPooling2D(pool_size=(2, 2)))
self.model.add(Dropout(0.5))
self.model.add(Flatten())
self.model.add(Dense(512))
self.model.add(Activation('relu'))
self.model.add(Dropout(0.5))
self.model.add(Dense(nb_classes))
self.model.add(Activation('softmax'))
self.model.summary()
数据集
# this will do preprocessing and realtime data augmentation
datagen = ImageDataGenerator(
featurewise_center=True, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=20, # randomly rotate images in the range (degrees, 0 to 180)
width_shift_range=0.2, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.2, # randomly shift images vertically (fraction of total height)
# rescale=1. / 255,
# shear_range=0.2,
# zoom_range=0.2,
horizontal_flip=True, # randomly flip images
vertical_flip=False) # randomly flip images
datagen.fit(dataset.X_train)
checkpoint = ModelCheckpoint(self.FILE_PATH, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
callback_list = [checkpoint]
# fit the model on the batches generated by datagen.flow()
train_generator = datagen.flow(dataset.X_train, dataset.Y_train, batch_size=batch_size, shuffle=True)
history = self.model.fit_generator(train_generator,
samples_per_epoch=dataset.X_train.shape[0],
nb_epoch=nb_epoch,
validation_data=(dataset.X_valid, dataset.Y_valid),
callbacks=callback_list)
答案 0 :(得分:4)
结果并不奇怪。网络从来没有学过什么让你的脸变得特别,但只记得是什么让500套与你的不同。一旦你呈现一张新面孔,它就没有它的“记忆”,因此将其解释为你的面孔,因为500面中没有任何特征出现在第501个。
如何解决这个问题的一些想法:
从最后一点对我的假设进行的一个很好的测试是可视化隐藏层中的激活,尤其是第一个隐藏层。我有一种感觉,你的网络激活一些不相关的功能(或者更确切地说 - 噪音),而不是“人类特征”(如眼睛,理发)。
[添加更多代码后编辑]
我仍然认为使用例如第一个隐藏层中的16或32个过滤器应该是第一个要检查的东西。看看你的脸。你能看到128个“功能”吗?除非你有一些严重的痤疮,否则我不这么认为。
答案 1 :(得分:2)
对于类似的分类任务,您没有足够的数据来处理250 + 500个样本。 A类(你)与B类(其他)之间的50/100关系是一个重要的偏见。至少你应该在训练时尝试使用.fit()函数中的class_weight参数进行均衡。
更好的方法是重新培训现有的ConvNet,如VGG16或来自Keras应用程序的Inception:https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html
您可以通过数据扩充轻松增加样本数量(请参阅此处的ImageDataGenerator https://keras.io/preprocessing/image/)。
为了分析您的代码,您需要展示如何拆分数据以及如何训练数据。正确的培训方式是分离列车数据和验证数据,而不是评估另一组独立的测试数据,网络从未见过,而且你还没有优化你的超参数。
据我对您的火车/测试/验证拆分的评论我可以看到:您是否从同一组图像中拆分了两次?这可能会在验证和测试数据中提供相同的图像,这反过来会导致错误的结果。
要查看您的培训代码会有所帮助。