【问题标题】:Error in Convolutional Neural network for input shape输入形状的卷积神经网络错误
【发布时间】:2018-05-31 18:31:19
【问题描述】:

我有 1000 张 28*28 分辨率的图像。我将这 1000 张图像转换为 numpy 数组,并形成了一个大小为 (1000,28,28) 的新数组。所以,虽然 使用keras创建卷积层,输入形状(X值)指定为(1000,28,28),输出形状(Y值)指定为(1000,10)。因为我哈 ve 1000 个示例是输入和 10 类输出。

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',kernel_initializer='he_normal',input_shape=(1000,28,28)))
.
.
.
model.fit(train_x,train_y,batch_size=32,epochs=10,verbose=1)

因此,在使用fit 函数时,它会将ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (1000, 28, 28) 显示为错误。请帮助我为 CNN 提供正确的输入和输出维度。

代码:

 model = Sequential()
 model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',kernel_initializer='he_normal',input_shape=(4132,28,28)))
 model.add(MaxPooling2D((2, 2)))
 model.add(Dropout(0.25))

 model.add(Conv2D(64, (3, 3), activation='relu'))
 model.add(MaxPooling2D(pool_size=(2, 2)))
 model.add(Dropout(0.25))

 model.add(Conv2D(128, (3, 3), activation='relu'))
 model.add(Dropout(0.4))

 model.add(Flatten())
 model.add(Dense(128, activation='relu'))
 model.add(Dropout(0.3))
 model.add(Dense(10, activation='softmax'))

 model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.Adam(),metrics=['accuracy'])
 model.summary()

 train_x  = numpy.array([train_x])

 model.fit(train_x,train_y,batch_size=32,epochs=10,verbose=1)

【问题讨论】:

    标签: python machine-learning neural-network deep-learning conv-neural-network


    【解决方案1】:

    您需要将输入更改为 4 维,将 channel 设置为 1 : (1000, 28, 28, 1) 并且需要将卷积层的 input_shape 更改为 (28, 28, 1):

    model.add(Conv2D(32, kernel_size=(3, 3),...,input_shape=(28,28,1)))
    

    【讨论】:

      【解决方案2】:

      您的 numpy 数组需要第四维,通用标准是使用第一维对样本进行编号,因此将 (1000, 28, 28) 更改为 (1, 1000, 28, 28)。

      您可以阅读有关此here 的更多信息。

      【讨论】:

      • 如果我将 (1000,28,28) 转换为 (1,1000,28,28) 则 ValueError: Input arrays should have the same number of samples as target arrays. Found 1 input samples and 1000 target samples. 正在发生
      • 您需要更改输入形状以获取单个样本。如果没有看到您的其余代码,我无法说出更多信息。
      【解决方案3】:

      从您的输入看来,您正在使用 tensorflow 作为后端。

      在 keras 中,input_shape 应始终为 3 维。 对于 tensorflow 作为后端,您的模型的 input_shape 将是

      input_shape = [img_height,img_width,channels(depth)]
      

      在您的情况下,张量流后端应该是

      input_shape = [28,28,1]
      

      train_x 的形状应该是

      train_x = [batch_size,img_height,img_width,channels(depth)]
      

      在你的情况下

      train_x = [1000,28,28,1]
      

      当您使用灰度图像时,图像的尺寸将为 (image_height, image_width),因此您必须为图像添加一个额外的尺寸,这将导致 (image_height, image_width, 1) '1 ' 表示图像的深度,灰度为“1”,RGB 为“3”。

      【讨论】:

        猜你喜欢
        • 2017-07-30
        • 2017-08-31
        • 2020-05-26
        • 2020-10-07
        • 2019-09-09
        • 1970-01-01
        • 2018-01-24
        • 2018-06-16
        • 1970-01-01
        相关资源
        最近更新 更多