【问题标题】:Python Neural Networks - Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (700, 128, 33)Python 神经网络 - 检查输入时出错:预期 conv2d_1_input 有 4 个维度,但得到了形状为 (700、128、33) 的数组
【发布时间】:2020-12-25 10:23:06
【问题描述】:

所以我正在开展一个“音乐流派分类”项目,我正在使用 GTZAN 数据集创建一个简单的 CNN 网络来对音频文件的流派进行分类。

我的模型训练、验证和测试代码如下:

input_shape = (genre_features.train_X.shape[1], genre_features.train_X.shape[2],1)
print("Build CNN model ...")
model = Sequential()

model.add(Conv2D(24, (5, 5), strides=(1, 1), input_shape=input_shape))
model.add(AveragePooling2D((2, 2), strides=(2,2)))
model.add(Activation('relu'))

model.add(Conv2D(48, (5, 5), padding="same"))
model.add(AveragePooling2D((2, 2), strides=(2,2)))
model.add(Activation('relu'))

model.add(Conv2D(48, (5, 5), padding="same"))
model.add(AveragePooling2D((2, 2), strides=(2,2)))
model.add(Activation('relu'))

model.add(Flatten())
model.add(Dropout(rate=0.5))

model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(rate=0.5))

model.add(Dense(10))
model.add(Activation('softmax'))
print("Compiling ...")
opt = Adam()
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
model.summary()

print("Training ...")
batch_size = 35  # num of training examples per minibatch
num_epochs = 400
model.fit(
    genre_features.train_X,
    genre_features.train_Y,
    batch_size=batch_size,
    epochs=num_epochs
)

print("\nValidating ...")
score, accuracy = model.evaluate(
    genre_features.dev_X, genre_features.dev_Y, batch_size=batch_size, verbose=1
)
print("Dev loss:  ", score)
print("Dev accuracy:  ", accuracy)


print("\nTesting ...")
score, accuracy = model.evaluate(
    genre_features.test_X, genre_features.test_Y, batch_size=batch_size, verbose=1
)
print("Test loss:  ", score)
print("Test accuracy:  ", accuracy)

# Creates a HDF5 file 'lstm_genre_classifier.h5'
model_filename = "lstm_genre_classifier_lstm.h5"
print("\nSaving model: " + model_filename)
model.save(model_filename)

当我尝试训练文件时,出现以下错误(我还在编译模型之前打印了训练、验证和测试形状)

Training X shape: (700, 128, 33)
Training Y shape: (700, 10)
Dev X shape: (200, 128, 33)
Dev Y shape: (200, 10)
Test X shape: (100, 128, 33)
Test Y shape: (100, 10)
Build CNN model ...
2020-12-25 15:46:58.410663: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
Compiling ...
Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_1 (Conv2D)            (None, 124, 29, 24)       624
_________________________________________________________________
average_pooling2d_1 (Average (None, 62, 14, 24)        0
_________________________________________________________________
activation_1 (Activation)    (None, 62, 14, 24)        0
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 62, 14, 48)        28848
_________________________________________________________________
average_pooling2d_2 (Average (None, 31, 7, 48)         0
_________________________________________________________________
activation_2 (Activation)    (None, 31, 7, 48)         0
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 31, 7, 48)         57648
_________________________________________________________________
average_pooling2d_3 (Average (None, 15, 3, 48)         0
_________________________________________________________________
activation_3 (Activation)    (None, 15, 3, 48)         0
_________________________________________________________________
flatten_1 (Flatten)          (None, 2160)              0
_________________________________________________________________
dropout_1 (Dropout)          (None, 2160)              0
_________________________________________________________________
dense_1 (Dense)              (None, 64)                138304
_________________________________________________________________
activation_4 (Activation)    (None, 64)                0
_________________________________________________________________
dropout_2 (Dropout)          (None, 64)                0
_________________________________________________________________
dense_2 (Dense)              (None, 10)                650
_________________________________________________________________
activation_5 (Activation)    (None, 10)                0
=================================================================
Total params: 226,074
Trainable params: 226,074
Non-trainable params: 0
_________________________________________________________________
Training ...
Traceback (most recent call last):
  File "cnn.py", line 82, in <module>
    epochs=400
  File "C:\Users\Bharat.000\miniconda3\lib\site-packages\keras\engine\training.py", line 1154, in fit
    batch_size=batch_size)
  File "C:\Users\Bharat.000\miniconda3\lib\site-packages\keras\engine\training.py", line 579, in _standardize_user_data
    exception_prefix='input')
  File "C:\Users\Bharat.000\miniconda3\lib\site-packages\keras\engine\training_utils.py", line 135, in standardize_input_data
    'with shape ' + str(data_shape))
ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (700, 128, 33)

我尝试了一些类似问题的解决方案,但由于我是这个主题的新手,所以我不太了解。任何关于我要改变什么以获得正确输出的帮助表示赞赏。

【问题讨论】:

    标签: python tensorflow machine-learning keras conv-neural-network


    【解决方案1】:

    您的输入尺寸错误。您确定您的数据是 2D(如图像)而不是 1D(如声波)吗?如果您的数据是一维数据,那么您应该进行一维卷积。发生错误的原因是因为您的训练数据具有形状 (700 (多少数据点), 128, 33)。在 keras 的 Conv2D 中,您需要拥有(批量大小、图像高度、图像宽度、通道)——通道可以是第一个或最后一个,但它并不真正相关。我想说的是,您只提供数字 128 而不是 2Dconv 所需的 (image_height, image_width) 元组。也许您正在寻找的是 1 Dimensional conv。

    【讨论】:

    • 感谢您的澄清,使用 Conv1d 解决了问题,并且我发现了它的原因。
    猜你喜欢
    • 2019-08-25
    • 2018-01-09
    • 2018-11-09
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多