1D卷积神经网络输入形状的`ValueError`

我在生成1D卷积时遇到了数据输入形状的问题。我查看了几篇帖子,似乎错误在于数据必须是3D的,但我的数据已经是3D的了。

# shape# x_train shape: (1228, 1452, 20)# y_train shape: (1228, 1452, 8)# x_val shape: (223, 680, 20)# x_val shape: (223, 680, 8)###n_outputs = 8n_timesteps = 1452n_features = 20model = Sequential()model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(x_train.shape[1:]))) # ie 1452, 20model.add(Conv1D(filters=64, kernel_size=3, activation='relu'))model.add(Dropout(0.5))model.add(MaxPooling1D(pool_size=2))model.add(Flatten())model.add(Dense(100, activation='relu'))model.add(Dense(n_outputs, activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])model.fit(x_train, y_train, epochs=9,                 batch_size=64,                 shuffle=True)

但我一直收到这个错误消息:

ValueError: A target array with shape (1228, 1452, 8) was passed for an output of shape (None, 8) while using as loss `categorical_crossentropy`. This loss expects targets to have the same shape as the output.

从中我了解到,目标形状是3维的,而输出是2维的,因此无法计算损失,但我只需要找到一种方法来重新调整形状,使它们相等。

编辑model.summary()如下所示

_________________________________________________________________Layer (type)                 Output Shape              Param #   =================================================================conv1d (Conv1D)              (None, 1450, 64)          3904      _________________________________________________________________conv1d_1 (Conv1D)            (None, 1448, 64)          12352     _________________________________________________________________dropout (Dropout)            (None, 1448, 64)          0         _________________________________________________________________max_pooling1d (MaxPooling1D) (None, 724, 64)           0         _________________________________________________________________flatten (Flatten)            (None, 46336)             0         _________________________________________________________________dense (Dense)                (None, 100)               4633700   _________________________________________________________________dense_1 (Dense)              (None, 8)                 808       =================================================================Total params: 4,650,764Traceback (most recent call last):Trainable params: 4,650,764Non-trainable params: 0

回答:

在我的案例中,问题在于目标向量是3D的,而输出向量是2D的,因此存在明显的不匹配。要解决这个问题,可以将y_train的形状更改为(batch, 8),或者使用return_sequences=True从前一层LSTM层返回相同形状的数据。

Related Posts

在使用k近邻算法时,有没有办法获取被使用的“邻居”?

我想找到一种方法来确定在我的knn算法中实际使用了哪些…

Theano在Google Colab上无法启用GPU支持

我在尝试使用Theano库训练一个模型。由于我的电脑内…

准确性评分似乎有误

这里是代码: from sklearn.metrics…

Keras Functional API: “错误检查输入时:期望input_1具有4个维度,但得到形状为(X, Y)的数组”

我在尝试使用Keras的fit_generator来训…

如何使用sklearn.datasets.make_classification在指定范围内生成合成数据?

我想为分类问题创建合成数据。我使用了sklearn.d…

如何处理预测时不在训练集中的标签

已关闭。 此问题与编程或软件开发无关。目前不接受回答。…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注