[英]Dimension problems: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (26, 26, 1)
I have a CNN that gets as input the following images converted by canny edge detection to a binary image.我有一个 CNN,它获取以下图像作为输入,这些图像通过精明的边缘检测转换为二值图像。 And outputs one of three categories.
并输出三个类别之一。
img = cv2.imread(path)
img = cv2.Canny(img, 33, 76)
img = np.resize(img, (26, 26, 1))
imgs.append(img)
As far I understood I have to convert it to a 3 dimensions (26,26,1) image so that the network can work with it.据我所知,我必须将其转换为 3 维(26,26,1)图像,以便网络可以使用它。 This is my network:
这是我的网络:
IMG_HEIGHT = 26
IMG_WIDTH = 26
no_Of_Filters=60
size_of_Filter=(5,5)
size_of_pool=(2,2)
no_Of_Nodes = 500
model_new = Sequential([
Conv2D(no_Of_Filters, size_of_Filter, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH , 1)),
MaxPooling2D(pool_size=size_of_pool),
Conv2D(no_Of_Filters, size_of_Filter, padding='same', activation='relu'),
MaxPooling2D(pool_size=size_of_pool),
Conv2D(64, size_of_Filter, padding='same', activation='relu'),
MaxPooling2D(pool_size=size_of_pool),
Flatten(),
Dense(512, activation='relu'),
Dense(3, activation='softmax')
])
Training works fine.训练效果很好。 After I trained and created a model I want to test images agains this network
在我训练并创建了一个模型之后,我想在这个网络上再次测试图像
test_image = cv2.Canny(test_image ,33,76)
test_image = np.resize(test_image, (26, 26, 1))
test_image = test_image [np.newaxis, ...]
prediction = model.predict(test_image)
print(prediction)
Now I get the error:现在我得到错误:
ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (26, 26, 1)
Why the trained model now wants a 4 dimensional input.为什么经过训练的模型现在需要 4 维输入。 I don't get this.
我不明白这个。
Solution解决方案
This is the new test code:
test_image = cv2.Canny(test_image ,33,76)
test_image = np.resize(test_image, (26, 26, 1))
test_image = test_image [np.newaxis, ...] # answer line added here
prediction = model.predict(test_image)
print(prediction)
You need to add a dimension to your array, because as the message says, keras
expects a 4D input.您需要为数组添加一个维度,因为正如消息所述,
keras
需要 4D 输入。
test_image = test_image[np.newaxis, ...]
keras
works with shapes such as (1, 26, 26, 1)
, not (26, 26, 1)
. keras
适用于诸如(1, 26, 26, 1)
形状,而不是(26, 26, 1)
。 The added first dimensions is the batch size and keras
needs it.添加的第一个维度是批量大小,
keras
需要它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.