为什么我的神经网络总是预测0

时间:2018-12-23 22:55:05

标签: python tensorflow machine-learning neural-network conv-neural-network

我想使用CNN对昏昏欲睡和非昏昏欲睡的面孔进行分类。我总共有28608张图像(通过增强创建)。我使用21456张图片进行训练,使用7152张图片进行测试,使用2000张图片进行验证。我得到准确度:0.93和损失:0.17

但是仍然,当我尝试从测试数据中随机预测少量图像时,它总是给出0。

有人可以帮我吗?

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
import os
import cv2
import random
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras

from sklearn.model_selection import train_test_split

print(tf.__version__)

DATADIR ="D:\\s1\\DATA"

CATEGORIES = ["D", "ND"]
IMG_SIZE = 50

training_data = []
#############################################################  0=Drowsy 1=NonDrowsy
def create_training_data():
    for category in CATEGORIES:  # do D and ND

        path = os.path.join(DATADIR,category)  # create path to D and ND
        class_num = CATEGORIES.index(category)  # get the classification  (0 or a 1). 0=D 1=ND

        for img in os.listdir(path):  # iterate over each image per D and ND
            try:
                img_array = cv2.imread(os.path.join(path,img) ,0)  # convert to array
                new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
                training_data.append([new_array, class_num])  # add this to  training_data
            except Exception as e:  # in the interest in keeping the output clean...
                pass

create_training_data()

random.shuffle(training_data)

x=[]
y=[]

for features,label in training_data:
    x.append(features)
    y.append(label)

x = np.array(x)
y = np.array(y)


####################################################################

X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=42)


####################################

X_train = X_train / 255.0
X_test = X_test / 255.0


X_train = X_train.reshape(X_train.shape[0], IMG_SIZE, IMG_SIZE, 1)
X_test = X_test.reshape(X_test.shape[0], IMG_SIZE, IMG_SIZE, 1)


model = keras.Sequential()

model.add(keras.layers.Conv2D(32, (3, 3), activation='relu',input_shape=(IMG_SIZE, IMG_SIZE, 1)))
model.add(keras.layers.Conv2D(32, (3, 3), activation='relu'))
model.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(keras.layers.Dropout(0.25))

model.add(keras.layers.Conv2D(64, (3, 3), activation='relu'))
model.add(keras.layers.Conv2D(64, (3, 3), activation='relu'))
model.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(keras.layers.Dropout(0.25))

model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(256, activation='relu'))
model.add(keras.layers.Dropout(0.5))
model.add(keras.layers.Dense(1, activation='sigmoid'))

model.summary()
model.compile(optimizer=tf.train.AdamOptimizer(),loss='binary_crossentropy',metrics=['accuracy'])

#Validation set
x_val = X_train[:2000]
partial_x_train = X_train[2000:]

y_val = y_train[:2000]
partial_y_train = y_train[2000:]

history = model.fit(partial_x_train, partial_y_train, epochs=5,batch_size=100, validation_data=(x_val, y_val),verbose=1)
###########
results = model.evaluate(X_test, y_test)
print(results)
################


for i in range(6):
    print(i)
    img1 = X_test[i]
    print(img1.shape)
    img1 = (np.expand_dims(img1,0))
    print(img1.shape)

    print('actual label')
    print(y_test[i])


    predictions_single = model.predict(img1)
    print('predicted label')

    print(predictions_single)
    print(np.argmax(predictions_single[0]))
    print('########################################')
    print('########################################')

1 个答案:

答案 0 :(得分:0)

与其尝试使列表training_data完全保持全局性,不希望函数create_training_data()从内部进行更新,而是尝试在函数中完全创建并返回:

#############################################################  0=Drowsy 1=NonDrowsy
def create_training_data():

    training_data = []

    for category in CATEGORIES:  # do D and ND
        path = os.path.join(DATADIR,category)  # create path to D and ND
        class_num = CATEGORIES.index(category)  # get the classification  (0 or a 1). 0=D 1=ND
        for img in os.listdir(path):  # iterate over each image per D and ND
            try:
                img_array = cv2.imread(os.path.join(path,img) ,0)  # convert to array
                new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
                training_data.append([new_array, class_num])  # add this to  training_data
            except Exception as e:  # in the interest in keeping the output clean...
                pass

    return training_data


training_data = create_training_data() 

您可能还需要考虑将其他变量作为参数传递给函数,以避免类似的问题。