gpt4 book ai didi

deep-learning - Keras:单个图像的model.predict

转载 作者:行者123 更新时间:2023-12-04 01:20:19 26 4
gpt4 key购买 nike

我想对Keras的单个图像做出预测。我已经训练了模型,所以我只是在加载重量。

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
import cv2

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



def create_model():
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'))

return model


img = cv2.imread('./test1/1.jpg')
model = create_model()
model.load_weights('./weight.h5')
model.predict(img)


我正在使用以下方式加载图像:

img = cv2.imread('./test1/1.jpg')


并使用模型的预测功能:

 model.predict(img)


但是我得到了错误:

ValueError: Error when checking : expected conv2d_1_input to have 4 dimensions, but got array with shape (499, 381, 3)


我应该如何对单个图像进行预测?

最佳答案

由于您是在迷你批次上训练模型的,因此您输入的是形状为[batch_size, image_width, image_height, number_of_channels]的张量。

进行预测时,即使只有一张图像,也必须尊重这种形状。您输入的内容应为:[1, image_width, image_height, number_of_channels]

您可以轻松地在numpy中执行此操作。假设您有一张5x5x3的图片:

    >>> x = np.random.randint(0,10,(5,5,3))
>>> x.shape
>>> (5, 5, 3)
>>> x = np.expand_dims(x, axis=0)
>>> x.shape
>>> (1, 5, 5, 3)


现在x是4级张量!

关于deep-learning - Keras:单个图像的model.predict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43017017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com