使用Tensorflow进行Python Keras图像识别model.predict返回[[0.]]

时间:2018-03-26 00:55:38

标签: python image-processing tensorflow keras image-recognition

我一直在关注教程here来处理猫的图像,并查看特定图片是否包含猫。我使用的数据集是here。我在图像中读取测试的方式是否缺少某些东西?在我的model.predict(filePath)的结果中,在读取包含cat的图像时,我总是得到值'[[0.]]'。列车和验证集似乎正常工作。我只是在阅读图像时遇到问题。 (源代码从here复制)

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
import numpy as np
from keras.preprocessing import image

# dimensions of our images.
img_width, img_height = 150, 150

train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
nb_train_samples = 2000
nb_validation_samples = 800
epochs = 50
batch_size = 16

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

model.save_weights('first_try.h5')


def _LoadImage(filePath):
    test_image = image.load_img(filePath, target_size = (150,150))
    test_image = image.img_to_array(test_image)
    test_image = np.expand_dims(test_image, axis=0)
    return test_image


test_this = _LoadImage('test.jpg')
result = model.predict(test_this)
print(result)

1 个答案:

答案 0 :(得分:0)

看起来" 0"是猫的标签("培训档案包含25,000张狗和猫的图像。在这些文件上训练你的算法并预测test1.zip的标签(1 =狗,0 =猫)。") ,所以你的模型预测似乎是正确的。请记住,模型是预测(猫和狗)标签,而不是您自己可能与标签对应的类字符串。尝试喂养狗的图像,你应该得到" 1"作为回报。