Keras模型重复输出0,没有错误
Posted
技术标签:
【中文标题】Keras模型重复输出0,没有错误【英文标题】:Keras model is outputting 0 repeatedly with no error 【发布时间】:2019-05-28 04:22:35 【问题描述】:我一直在使用带有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】: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
作为损失函数。或者,您可以对标签进行 one-hot 编码,然后使用 categorical_crossentropy
作为损失函数。
【讨论】:
以上是关于Keras模型重复输出0,没有错误的主要内容,如果未能解决你的问题,请参考以下文章
分配器(GPU_0_bfc)在使用纯张量流时尝试分配内存不足,而在 keras 上更复杂的模型上没有错误