python - 如何导入训练好的模型来预测单张图像?

标签 python tensorflow machine-learning deep-learning keras

我通过 Keras 训练了一个 CNN 模型,并通过 model.save('model.h5') 保存了模型。 但我想在单个图像上测试我的模型,我不知道如何将我自己的图像导入到我的模型中。

# Image generators
train_datagen = ImageDataGenerator(rescale= 1./255)
validation_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(  
    train_data_dir,
    target_size=(image_size, image_size),
    shuffle=True,
    batch_size=batch_size,
    class_mode='categorical'
    )

validation_generator = validation_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(image_size, image_size),
    batch_size=batch_size,
    shuffle=True,
    class_mode='categorical'
    )

# Fit model
history = model.fit_generator(train_generator,
                steps_per_epoch=(nb_train_samples // batch_size),
                epochs=nb_epoch,
                validation_data=validation_generator,
                callbacks=[early_stopping],# save_best_model],
                validation_steps=(nb_validation_samples // batch_size)
               )

# Save model
model.save_weights('full_model_weights.h5')
model.save('model.h5')

我是 keras 的新手。我该如何将图像处理给我的模型并将我的图像分类到某个类别。

输入的形状:

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

我的导入图像的代码:

from keras.models import load_model
m=load_model("model.h5")

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

cloudy_pic="./Weather/weather_database/cloudy/4152.jpg"
im=Image.open(cloudy_pic).convert('RGB')
data=np.array(im,dtype=np.float32)
data=np.reshape(500, 500,3)
pre=m.predict_classes(data)
pre

错误:

AttributeError: 'int' object has no attribute 'reshape'
During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-30-ebc72e185819> in <module>()
     10 im=Image.open(cloudy_pic).convert('RGB')
     11 data=np.array(im,dtype=np.float32)
---> 12 data=np.reshape(500, 500,3)
     13 pre=m.predict_classes(data)
     14 pre

~/anaconda3/envs/tensorflow/lib/python3.6/site- packages/numpy/core/fromnumeric.py in reshape(a, newshape, order)
    230            [5, 6]])
    231     """
--> 232     return _wrapfunc(a, 'reshape', newshape, order=order)
    233 
    234 

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     65     # a downstream library like 'pandas'.
     66     except (AttributeError, TypeError):
---> 67         return _wrapit(obj, method, *args, **kwds)
     68 
     69 

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/numpy/core/fromnumeric.py in _wrapit(obj, method, *args, **kwds)
     45     except AttributeError:
     46         wrap = None
---> 47     result = getattr(asarray(obj), method)(*args, **kwds)
     48     if wrap:
     49         if not isinstance(result, mu.ndarray):

ValueError: cannot reshape array of size 1 into shape (500,)

最佳答案

您可以在将图像转换为 np 数组之前调整图像大小。

img = Image.open(img_path)
img = img.resize((image_size,image_size))
img = np.array(img)
img = img / 255.0
img = img.reshape(1,image_size,image_size,3)
m.predict_classes(img)

模型的输入形状必须为 [None,image_size,image_size,3][None,3,image_size,image_size](如果 channels_first) .

关于python - 如何导入训练好的模型来预测单张图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50128278/

相关文章:

python - 根据条件将值应用于数字的所有实例

python - 类似 SQL 的 MAX 和 GROUP BY 在字典列表上

macos - 错误 : Could not find a version that satisfies the requirement tensorflow-text==2. 8.*(来自版本:无)

python - Tensorflow Hub 和 JS : how to fine-tune a pre-trained model and export it for using in Tensorflow. js?

java - Weka 错误消息 - 没有足够的带有类标签的训练实例(需要 : 1, 提供 : 0)!

python - 获取类型错误 : '(slice(None, None, None), 0)' is an invalid key

python - 在 Python 中,如何根据年份、周数和工作日获取日期?

python-3.x - tensorflow : Using Queue for CSV file with custom Estimator and "input_fn" function

r - 在 R 中的文本文件中输出 J48 树

python - 在 tfp 中训练变分贝叶斯神经网络时,如何分别可视化损失中不同项的演化?