Keras中conv2d的input_shape和手动加载图像的问题

16

我正在手动创建我的数据集,这些数据集由一系列384x286的黑白图像组成。

我像这样加载一个图像:

x = []
for f in files:
        img = Image.open(f)
        img.load()
        data = np.asarray(img, dtype="int32")
        x.append(data)
x = np.array(x)

这导致x成为一个数组(num_samples,286,384)。

print(x.shape) => (100, 286, 384)
阅读Keras文档并检查我的后端,我应该向卷积步骤提供一个由(行、列、通道)组成的input_shape。

由于我不会随意知道样本大小,所以我希望将一个类似于这样的输入大小传递给它。

( None, 286, 384, 1 )

模型的构建如下:

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))
# other steps...

将 (286, 384, 1) 作为输入形状会导致以下问题:

检查输入时出错:期望 conv2d_1_input 具有 4 个维度,但得到的数组形状为 (85, 286, 384)

将 (None, 286, 384, 1) 作为输入形状会导致以下问题:

输入 0 与层 conv2d_1 不兼容:期望 ndim=4,但发现 ndim=5

我做错了什么?我该如何重新调整输入数组的形状?

3个回答

21

input_shape设置为(286,384,1)。现在该模型期望具有四个维度的输入。这意味着您需要使用.reshape(n_images, 286, 384, 1)来重新调整图像。现在,您已经添加了一个额外的维度而没有更改数据,您的模型已准备好运行。基本上,您需要将数据重塑为(n_images, x_shape, y_shape, channels)。

很酷的是,你也可以使用RGB图像作为输入。只需将channels更改为3即可。

还可以查看以下回答:Keras input explanation: input_shape, units, batch_size, dim, etc

示例

import numpy as np
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D
from keras.layers.core import Flatten, Dense, Activation
from keras.utils import np_utils

#Create model
model = Sequential()
model.add(Convolution2D(32, kernel_size=(3, 3), activation='relu', input_shape=(286,384,1)))
model.add(Flatten())
model.add(Dense(2))
model.add(Activation('softmax'))

model.compile(loss='binary_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])

#Create random data
n_images=100
data = np.random.randint(0,2,n_images*286*384)
labels = np.random.randint(0,2,n_images)
labels = np_utils.to_categorical(list(labels))

#add dimension to images
data = data.reshape(n_images,286,384,1)

#Fit model
model.fit(data, labels, verbose=1)

7
谢谢,我错过了重新塑形的部分。 通俗易懂地说,对于任何在未来跟进此讨论的人,当表示数据时,像素值必须是1元素数组,例如,像素的单行不应该是 [100,101,140,...] 这样的形式,而应该是 [[100], [101], [140], ...]。 - Stormsson

4

您的 input_shape 尺寸是正确的,即 input_shape(286, 384, 1)

将您的 input_image 重塑为 4D [batch_size, img_height, img_width, number_of_channels]

input_image=input_image.reshape(85,286, 384,1)

在……期间

model.fit(input_image,label)

1

我认为以下内容可能会解决您的错误。

  1. 我们提供给顺序模型的第一层 conv2d 的 input_shape 应该是类似于 (286,384,1) 或者 (width,height,channels)。其中不需要 "None" 维度来表示 batch_size。

  2. 您的输入形状可以是 (batch_size,286,384,1)

这对您有帮助吗?


你的建议正是我之前尝试过的,而且它们导致了我写的这两个错误。 - Stormsson
你的输入形状应该为(batch_size, width, height, 1),而不仅仅是(batch_size, width, height)。 - Harsha Pokkalla
它导致错误“输入0与层conv2d_1不兼容:期望ndim = 4,但发现ndim = 5” - Stormsson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接