简体   繁体   English

TensorFlow/Keras model 在尝试预测时出错,引用形状不匹配,尽管我提供的形状似乎正确

[英]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.

相关问题 TensorFlow2 / Keras:当子类化 keras.Model 时 input_shape 似乎没有效果 - TensorFlow2 / Keras: input_shape seems to not have an effect when subclassing keras.Model 使用Keras(Tensorflow)训练模型时出现形状错误 - Shape error when training a model with Keras (Tensorflow) 预测和拟合之间的keras形状不匹配 - keras shape mismatch between predict and fit 与 keras-turner 一起使用时 tensorflow CNN model 的输入形状不匹配 - Input shape mismatch of tensorflow CNN model when use with keras-turner Keras / Tensorflow预测:阵列形状的错误 - Keras/Tensorflow predict: error in array shape Keras:模型预测,检查输入形状时出错 - Keras: Model Predict, Error When Checking Input Shape Keras:尝试 model.predict() 给出“ValueError:张量的形状与提供的形状不兼容” - Keras: Trying to model.predict() gives “ValueError: Tensor's shape is not compatible with supplied shape” Keras-与model.predict()不匹配的数组形状 - Keras - mismatched array shape with model.predict() Tensorflow.keras:输入的形状是(),即使形状是(768、8) - Tensorflow.keras: Shape of input is (), EVEN THOUGH SHAPE IS (768, 8) Keras RNN,输入的形状不正确,即使形状显示为正确 - Keras RNN, incorrect shape of input even though shape is shown as correct
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM