Skip to main content
 首页 » 编程设计

python之使用 Keras 的 ImageDataGenerator 预测单个图像

2024年11月01日17hnrainll

我是深度学习的新手,所以请原谅我提出这个可能很简单的问题。

我训练了一个网络来在 positive 和 negative 之间进行分类。为了简化图像生成和拟合过程,我使用了 ImageDataGenerator 和 fit_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。我已经在我的 validation_generator 上尝试了 model.predict_generator(),它有效,但这不是单个图像。

提前致谢。

请您参考如下方法:

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

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)。因此,在进行预测之前,将图像的维度扩展为一批单个图像。