使用Keras的ImageDataGenerator预测单个图像

时间:2019-08-26 13:09:51

标签: python tensorflow keras deep-learning

我对深度学习还很陌生,所以请原谅我这个可能很简单的问题。

我训练了一个网络来对positivenegative进行分类。为了简化图像生成和拟合过程,我使用了ImageDataGeneratorfit_generator函数,如下所示:

import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator

# Simplified model
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(12, 12, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

# Image import, for 'validation_generator' equally
train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
    './training/',
    target_size=(12, 12),
    batch_size=128,
    class_mode='binary')

# Compiling
model.compile(loss='binary_crossentropy',
             optimizer='adam',
             metrics=['acc'])

# Fitting, for Tensorboard 'history = model.fit_gen...'
model.fit_generator(train_generator,
                    steps_per_epoch=8,
                    epochs=50,
                    verbose=1,
                    validation_data = validation_generator,
                    validation_steps=8,
                    callbacks=[tb]) # Standard Tensorboard

我想用我的模型预测单个图像(导入为numpy array),如下所示:

image = 'single imported image with shape (12, 12, 3)'
model.predict(image)

但是,我唯一得到的是一条错误消息,指出Matrix size-incompatible。我已经在model.predict_generator()上尝试过validation_generator了,但是效果不佳。

谢谢。

1 个答案:

答案 0 :(得分:1)

如果要对单个图像进行预测,请执行以下操作:

image = np.random.rand(12, 12, 3) # single imported image with shape (12, 12, 3)
image = np.expand_dims(image, axis=0) # image shape is (1, 12, 12, 3)
model.predict(image)

换句话说,您的模型仍然期望输入形状为(None, 12, 12, 3)。因此,在进行预测之前,请将图像的尺寸扩展为单个图像的批处理。