【问题标题】:My model keeps predicting the same face, how can i fix it?我的模型一直在预测同一张脸,我该如何解决?
【发布时间】:2020-09-14 06:58:35
【问题描述】:

我使用 CNN 训练了一个模型,并将其与 opencv 一起用于网络摄像头上的实时人脸识别。我的模型有一些问题,比如我在训练时获得了 100% 的准确率,而且我知道肯定出了问题,另一个问题是,当它在网络摄像头图像上进行预测时,无论我展示谁的脸,它都只会给我一个标签: 无论我是露脸还是别人的脸,它都会给一个“我”的标签。

注意,我的数据集中只有 250 张图像:200 张图像用于训练,50 张图像用于测试。对于每组,我将它们分为 2 个类别,“me”和“not_me”,其中“me”文件夹包含我的脸部图像,“not_me”文件夹包含不同人脸的图像。

模型的数据还是不够用?

请帮助我从错误中吸取教训。先谢谢了。

myface_model.py

​​>
# Importing the Keras libraries and packages
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.preprocessing.image import ImageDataGenerator

# Initialising the CNN
classifier = Sequential()

# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))

# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 3 - Flattening
classifier.add(Flatten())

# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))

# output layer
classifier.add(Dense(units = 1, activation = 'sigmoid'))

# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

# Part 2 - Fitting the CNN to the images
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('dataset/training_set',
                                                 target_size = (64, 64),
                                                 batch_size = 32,
                                                 class_mode = 'binary')

test_set = test_datagen.flow_from_directory('dataset/test_set',
                                            target_size = (64, 64),
                                            batch_size = 32,
                                            class_mode = 'binary')

classifier.fit_generator(training_set,
                         steps_per_epoch = 200,
                         epochs = 25,
                         validation_data = test_set,
                         validation_steps = 50)

#save model for later use
fer_json = classifier.to_json()
with open("fer.json", "w") as json_file:
    json_file.write(fer_json)
classifier.save_weights("fer.h5")

myface_detector.py

​​>
import os
import cv2
import numpy as np
from keras.models import model_from_json
from keras.preprocessing import image

#load model
classifier = model_from_json(open("fer.json", "r").read())
#load weights
classifier.load_weights('fer.h5')

face_haar_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

cap=cv2.VideoCapture(0)

while True:
    # captures frame and returns boolean value and captured image
    ret,test_img=cap.read()

    if not ret:
        continue

    convt_img= cv2.cvtColor(test_img, cv2.COLOR_BGR2RGB)

    faces_detected = face_haar_cascade.detectMultiScale(convt_img, 1.3, 5)

    for (x,y,w,h) in faces_detected:
        cv2.rectangle(test_img, (x,y), (x+w,y+h), (255,0,0), thickness=4)
        roi = convt_img[y:y+h,x:x+w]
        roi = cv2.resize(roi,(64,64))
        roi = roi.astype("float") / 255.0
        img_pixels = image.img_to_array(roi)
        img_pixels = np.expand_dims(img_pixels, axis = 0)

        predictions = classifier.predict(img_pixels)

        #find max indexed array
        max_index = np.argmax(predictions[0])

        myFace = ('me', 'not_me')

        predicted_myFace = myFace[max_index]

        cv2.putText(test_img, predicted_myFace, (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)

    cv2.imshow('my face predictions',test_img)

    if cv2.waitKey(10) == ord('q'):#wait until 'q' key is pressed
        break

cap.release()
cv2.destroyAllWindows()

【问题讨论】:

  • 这感觉像是数据不足的情况。只是为了更深入一点,你是如何在网络摄像头上显示其他人的脸的?它们都在相同的照明条件下吗?您能否尝试将您的模型拆分为 train:validation:test 集,然后在测试集而不是网络摄像头输入上测试您的模型。

标签: python tensorflow machine-learning keras deep-learning


【解决方案1】:

二进制类

所以问题的症结在于我们如何选择表示我们的模型。具体在以下几行:

classifier.add(Dense(units = 1, activation = 'sigmoid'))

training_set = train_datagen.flow_from_directory('dataset/training_set',
                                                 target_size = (64, 64),
                                                 batch_size = 32,
                                                 class_mode = 'binary') #<--------

test_set = test_datagen.flow_from_directory('dataset/test_set',
                                            target_size = (64, 64),
                                            batch_size = 32,
                                            class_mode = 'binary') #<-------------

这里我们选择给我们的 CNN 一个输出节点并具有二进制类标签。这意味着predict 方法的返回值将类似于[[0.12956393]]。该值表示测试图像具有类标签 1(在这种情况下,标签为“not_me”)的预测概率。要提取类标签,我们可以简单地这样做:

predictions = classifier.predict(img_pixels)
predicted_label = predictions[0][0] > 0.5
myFace = ('me', 'not_me')
predicted_myFace = myFace[predicted_label]

但是,为了遵循原始代码的意图,根据最高概率选择类标签,并允许我们扩展此应用程序以在需要时轻松预测更多类,我们只需对模型进行少量修改即可使用分类标签。

分类类

我们可以使用分类标签,而不是使用二进制标签。这将允许我们从 0...n 获得类标签。在这种情况下,我们只需要进行以下编辑

classifier.add(Dense(units = 2, activation = 'sigmoid')) # note that units = 2 now

training_set = train_datagen.flow_from_directory(
    'dataset/training_set',
    target_size = (64, 64),
    batch_size = 32,
    class_mode = 'categorical') # note the new class mode

test_set = test_datagen.flow_from_directory(
    'dataset/test_set',
    target_size = (64, 64),
    batch_size = 32,
    class_mode = 'categorical') # note the new class mode

通过为我们的 CNN 提供两个输出节点并将类别模式从二进制更改为分类,我们的 CNN 现在能够输出每个类别标签的预测概率。即predict 方法的返回值将类似于:

[[0.012211  0.9917401]]

这意味着您在 myface_detector.py 中的代码将按原样运行。

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 2012-06-19
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多