ValueError: Input 0 of layer sequential_3 is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (None, 224, 256)

ValueError: Input 0 of layer sequential_3 is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (None, 224, 256)

我是 Keras 的新手,我正在尝试创建一个将 (224,256,1) 大小的图像作为输入的 CNN。

这是我不断收到的错误:

    ValueError: Input 0 of layer sequential_5 is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (None, 224, 256)

我对错误的解释是图层获得的数据有 3 个维度,而图层至少需要 4 个维度。根据keras documentation,输入形状应该是(batch size, x , y , channels)。我只使用单个图像,因为我认为批量大小应该只是 1.

制作模型的代码如下:

model = keras.Sequential([
                          keras.layers.Conv2D(filters=32, kernel_size=(3,3), activation="relu", padding='same', input_shape=(224,256,1), data_format='channels_last'),
                          keras.layers.MaxPool2D(pool_size=(2,2), padding='same'), 
                          keras.layers.Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same'),
                          keras.layers.MaxPool2D(pool_size=(2,2), padding='same'), 
                          keras.layers.Flatten(),
                          keras.layers.Dense(8, activation="softmax")
])

预测代码如下:

img = get_image()
img = convert_to_greyscale(img)
img = tf.expand_dims(img, axis=0) # add dimension to represent batch to the front
prediction = model.predict(img) # ValueError Input 0 of sequential_3 ...

如果您需要更多信息,请告诉我,谢谢!

您需要将 one dimension 添加到图像,然后 expand_dims 作为 batch,如下所示:(将图像调整为模型的大小)

from skimage import io
img = io.imread('1.jpeg', as_gray=True)[...,None]
img = tf.image.resize(img, [224, 256])
# ------------------------- ^^^  ^^^ this is size of your input model
img = tf.expand_dims(img, axis=0)
model.predict(img) 

输出:

array([[0.1329774 , 0.1408476 , 0.13449876, 0.10563403, 0.11976303,
        0.12162709, 0.12393728, 0.12071485]], dtype=float32)