[英]TensorFlow/Keras model errors out when trying to predict, citing shape mismatch, though the shape I provide seems correct
I am not sure if I don't understand the input tensor ideas well or if I trained the model with wrong input shapes, or if I need to specify images in a certain way.我不确定我是否不太了解输入张量的想法,或者我是否用错误的输入形状训练了 model,或者我是否需要以某种方式指定图像。
The model is built as follows: model 构建如下:
... import all the usual libraries - TF, Keras, Numpy, OpenCV etc. ...
_MODEL_DIMENSION = 128
def create_model_for_dimension(dimension):
model = Sequential()
if dimension >= 256:
model.add(Conv2D(256, kernel_size=(5, 5), input_shape=(dimension, dimension, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
if dimension >= 128:
model.add(Conv2D(128, kernel_size=(3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
…… more convolution layers ……..
…………………………………………..
……………………………………………..
model.add(Flatten())
……… More layers …………………
……………………………………………..
……………………………………………..
model.add(Dense(2))
model.add(Activation('sigmoid'))
model.compile(loss='categorical_crossentropy',
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy'])
return model
train_datagen = ImageDataGenerator(
rotation_range=10,
width_shift_range=0.2,
height_shift_range=0.2,
rescale=1./255,
shear_range=0.2,
zoom_range=1.2,
horizontal_flip=True,
vertical_flip=True,
fill_mode='nearest')
train_generator = train_datagen.flow_from_directory(
train_data_directory,
target_size=(_MODEL_DIMENSION, _MODEL_DIMENSION),
batch_size=_BATCH_SIZE,
class_mode='categorical')
……… validate_generator …………………
……………………………………………………
………………………………………………………
……… test_generator ………………………
………………………………………………………
………………………………………………………
……… train and save the model ……
When I trained and used it to predict on images from a directory, everything worked (or seemed to, at least).当我训练并使用它来预测目录中的图像时,一切正常(或至少看起来)。 But I then tried to feed in an image without using the ImageDataGenerator in the following way:
但是我随后尝试通过以下方式在不使用 ImageDataGenerator 的情况下输入图像:
First, I read the image using OpenCV (I expect to do other processing using OpenCV, so am not using PIL)首先,我使用 OpenCV 读取图像(我希望使用 OpenCV 进行其他处理,所以我不使用 PIL)
ml_model = … read the model back from the saved model ……
snapshot = cv.imread(file_name)
snapshot = cv.cvtColor(snapshot, cv.COLOR_BGR2RGB)
Then I crop the image using ranges然后我使用范围裁剪图像
cropped_area = snapshot[y[0]:y[1], x[0]:x[1]]
Then I score using the model as follows.然后我使用 model 评分如下。 I also tried variants other than np.array conversion.
我还尝试了 np.array 转换以外的变体。
score_val = model.predict(np.array(cropped_area/255.0))
This is when it errors out as follows:这是当它出现如下错误时:
ValueError: Input 0 of layer sequential is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [32, 128, 3]
My image's shape is (128, 128, 3), and all the checks I made seem to confirm that that is what I have been feeding it.我的图像的形状是 (128, 128, 3),我所做的所有检查似乎都证实了我一直在喂它。
Any pointers would be greatly appreciated, since I have spent the better part of the day trying to troubleshoot this!任何指针将不胜感激,因为我花了一天的大部分时间试图解决这个问题! Thanks!
谢谢!
You set _MODEL_DIMENSION = 128
您设置
_MODEL_DIMENSION = 128
which leads to这导致
if dimension >= 128:
model.add(Conv2D(128, kernel_size=(3, 3)))
You do not set an input shape, so according to the documentation the expected input will be:您没有设置输入形状,因此根据文档,预期输入将是:
Input shape
输入形状
4D tensor with shape: (batch, channels, rows, cols) if data_format is "channels_first" or 4D tensor with shape: (batch, rows, cols, channels) if data_format is "channels_last".
具有形状的 4D 张量: (batch, channels, rows, cols) 如果 data_format 是 "channels_first" 或具有形状的 4D 张量: (batch, rows, cols, channels) 如果 data_format 是 "channels_last"。
Your input doesn't fit, hence the error您的输入不合适,因此出现错误
expected ndim=4, found ndim=3
预期 ndim=4,发现 ndim=3
The solution is to define an input shape, which already exists in your code:解决方案是定义一个输入形状,它已经存在于您的代码中:
if dimension >= 256:
model.add(Conv2D(256, kernel_size=(5, 5), input_shape=(dimension, dimension, 3)))
Your data is missing the batch dimension.您的数据缺少批次维度。 Your model needs 4D data, not 3D.
您的 model 需要 4D 数据,而不是 3D。
Your image shape should be (1, 128,128, 3)
您的图像形状应为
(1, 128,128, 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.