Keras模型重复输出0,没有错误

时间:2018-12-31 19:20:47

标签: python tensorflow machine-learning keras face-recognition

我一直在使用Keras模型和cv2人脸检测脚本来进行人脸识别。我最近遇到了一个问题,该模型在进行预测时会输出0。这特别奇怪,因为标签数组中没有0。顺便说一句,我有一个名为opencvtrainer的目录,它包含另外3个目录,每个目录都包含人脸图像。这是代码:

import PIL as PIL
import tensorflow as tf
import numpy as np
import cv2 as cv2
import os
# goes to opencvtrainer directory
basedir = os.path.dirname(os.path.abspath(__file__))
imagedir = os.path.join(basedir, "opencvtrainer")
ylabels = []
# if directory person: id
labelids = {
    "john_": 001,
    "erin_": 002,
    "scott_": 003,
    "colin_": 004
}
''' "glenn_": 004,
   "faith_": 005,
'''

xtrain = []
xl = []
# make general face classifier
# creates AI needing training
# goes through files in files in the opencvtrainer directory
fc = cv2.CascadeClassifier("lib/python2.7/site-package\
s/cv2/data/haarcascade_frontalface_alt2.xml")
for root, dirs, files in os.walk(imagedir):
    for file in files:
        if "png" in file:
            # path to file
            path = os.path.join(root, file)

            # whose file it is
            label = os.path.basename(root)

            # gets image
            imagep = PIL.Image.open(path)

            # convets image into greyscale then numpy array
            imagear = np.array(imagep.convert("L"), "uint8")
            imagearre = imagear
            face = fc.detectMultiScale(imagearre)

            for (x, y, w, h) in face:
                # makes roi for face
                roi = imagearre[y:y + h, x:x + w]
                roi = cv2.resize(roi, (70, 70))
                # gives that np array to xtrain
                xtrain.append(roi)
                print(roi.shape)
                # gives ylabels a num for all files it opened
                xl.append(labelids[label])


xtrain = np.array(xtrain)
ylabels = np.array(xl)
#adds AI from keras
model = tf.keras.models.Sequential()
# tells what an input should be & does crap w/ current input
model.add(tf.keras.layers.Flatten(input_shape=(70, 70)))
# adds layer
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
# adds layer
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
# adds layer
model.add(tf.keras.layers.Dense(1, activation=tf.nn.softmax))
# tests for accuracy
model.compile(optimizer="adam", loss="binary_crossentropy", metrics= . 
['accuracy'])
print(ylabels)
model.fit(xtrain, ylabels, epochs=3)
model.save("test11")'

1 个答案:

答案 0 :(得分:3)

1)将最后一层的单位数更改为4(因为有4个不同的类):

tf.keras.layers.Dense(4, activation=tf.nn.softmax)

2)从0开始,而不是从1开始编号标签。

labelids = {"john_": 0, "erin_": 1, "scott_": 2, "colin_": 3}

3)使用sparse_categorical_crossentropy作为损失函数。另外,您可以对标签进行一次热编码,然后使用categorical_crossentropy作为损失函数。