[英]ValueError: Input 0 of layer conv2d is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [None, 30, 30]
Hi I'm trying to build a simple CNN Model that is used for classification.I'm getting the below error.Thanks for the help in advance您好,我正在尝试构建一个用于分类的简单 CNN Model。我收到以下错误。提前感谢您的帮助
path=os.listdir(imgs_path)
data = []
labels = []
flag=0
classes = len(list_dir)
for i in path:
img_path = imgs_path +i + os.sep
for img in os.listdir(img_path):
im = Image.open(img_path + os.sep + img)
im = im.resize((30,30))
im = np.array(im)
data.append(im)
labels.append(flag)
flag=flag+1
x_train = np.array(data)
y_train = np.array(labels)
model = Sequential()
model.add(Conv2D(filters=32, kernel_size=(5,5), activation="relu",input_shape=x_train.shape[1:]))
model.add(Conv2D(filters=32, kernel_size=(5,5), activation="relu"))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(rate=0.25))
model.add(Conv2D(filters=64, kernel_size=(3,3), activation="relu"))
model.add(Conv2D(filters=64, kernel_size=(3,3), activation="relu"))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(rate=0.5))
model.add(Flatten())
model.add(Dense(256, activation="relu"))
model.add(Dropout(rate=0.25))
model.add(Dense(classes, activation="softmax"))
model.compile(loss="sparse_categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
ValueError: Input 0 of layer conv2d is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [None, 30, 30]
However it works for some images but not all,Not sure why this happens然而它适用于一些图像但不是全部,不知道为什么会这样
Conv2d layer expects images in batches, so try adding a batch dimension to the input. Conv2d 层需要批量处理图像,因此请尝试向输入添加批量维度。
You might be giving the input images in the shape of the images only, like for example (224,224,3) as in 224X224 image_size with 3 color channels.您可能仅以图像的形状提供输入图像,例如 (224,224,3),如 224X224 image_size 和 3 个颜色通道。
Try doing:尝试做:
x_train = np.expand_dims(x_train,axis=0)
this will expand the image dimensions from (224,224,3) to (1,224,224,3), adding an extra batch_size dimension as in the 4 dimensions the conv2d layer expects.这会将图像尺寸从 (224,224,3) 扩展到 (1,224,224,3),添加一个额外的 batch_size 尺寸,就像 conv2d 层期望的 4 个尺寸一样。
Some of your images are b&w, they have only 2 dimensions.你的一些图像是黑白的,它们只有二维。 Use
numpy.atleast_3d
.使用
numpy.atleast_3d
。 This will add a dimension if there are only 2, and not change arrays with already 3 dims.如果只有 2 个维度,这将添加一个维度,并且不会将 arrays 更改为已经有 3 个维度。
...
im = im.resize((30,30))
im = np.atleast_3d(im)
data.append(im)
...
So if you have a color image, for example (30, 30, 3)
, it will not be changed.所以如果你有一个彩色图像,例如
(30, 30, 3)
,它不会被改变。 But if you have ab/w image with shape (30, 30)
, it will be reshaped to (30, 30, 1)
但是如果你有形状为
(30, 30)
的 ab/w 图像,它将被重塑为(30, 30, 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.