我是Keras的新手,我正在尝试创建一个CNN,它将(224,256,1)
大小的图像作为输入。
这是我一直得到的错误:
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文档,输入形状应该是(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)