卷积神经网络input_shape维度错误(KERAS,PYTHON)

Convolution Neural Network input_shape dimension error (KERAS ,PYTHON)

我有一个如下形状的火车数据集:(300, 5, 720)

 [[[   6.   11.  389. ...,    0.    0.    0.]
   [   2.    0.    0. ...,   62.    0.    0.]
   [   0.    0.   18. ...,    0.    0.    0.]
   [  38.  201.   47. ...,    0.  108.    0.]
   [   0.    0.    1. ...,    0.    0.    0.]]

   [[ 136.   95.    0. ...,    0.    0.    0.]
   [  85.   88.   85. ...,    0.   31.    0.]
   [   0.    0.    0. ...,    0.    0.    0.]
   [   0.    0.    0. ...,    0.    0.    0.]
   [  13.   19.    0. ...,    0.    0.    0.]]]

我正在尝试将每个样本作为输入传递给 cnn 模型,每个输入的大小为 (5,720) ,我在keras中使用以下模型:

    cnn = Sequential()

    cnn.add(Conv2D(64, (5, 50),
    padding="same",
    activation="relu",data_format="channels_last",
    input_shape=in_shape))

   cnn.add(MaxPooling2D(pool_size=(2,2),data_format="channels_last"))

   cnn.add(Flatten())
   cnn.add(Dropout(0.5))

   cnn.add(Dense(number_of_classes, activation="softmax"))

   cnn.compile(loss="categorical_crossentropy", optimizer="adam", metrics=
   ['accuracy'])

   cnn.fit(x_train, y_train,
     batch_size=batch_size,
     epochs=epochs,
     validation_data=(x_test, y_test),
     shuffle=True)

我将输入形状用作:

    rows,cols=x_train.shape[1:]
    in_shape=(rows,cols,1)

但我收到以下错误:

ValueError: Error when checking model input: expected conv2d_1_input to have 4 dimensions, but got array with shape (300, 5, 720)

我该如何解决这个错误?

这是Keras中Convolutions最经典的错误之一。它的起源在于这样一个事实,即在使用 channels_last 输入维度时,即使只有一个通道,您也需要使输入具有维度 (height, width, channels) 。所以基本上重塑:

x_train = x_train.reshape((x_train.shape[0], 5, 720, 1)

应该可以解决您的问题。