gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:28:16 25 4
gpt4 key购买 nike

我一直致力于使用带有 cv2 人脸检测脚本的 Keras 模型来进行人脸识别。我最近遇到一个问题,模型每次做出预测时都会输出 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) 将最后一层的单元数更改为 4(因为您有 4 个不同的类):

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

2)从零开始对标签编号,而不是从一:

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

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

关于python - Keras 模型重复输出 0,没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53990774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com