Keras/Tensorflow Conv1D 预期输入形状

Keras/Tensorflow Conv1D expected input shape

我想对我的 29 个特征输入数据(如 29x1 形状)应用一维卷积。我告诉 Keras input_shape=(29,1),但我得到一个错误,它期望输入 "to have 3 dimensions, but got array with shape (4000, 29)"。 为什么 Keras 需要 3 个维度?

Keras 文档给出了这个奇怪的例子来说明如何使用 input_shape:

(None, 128) for variable-length sequences with 128 features per step.

我不确定可变长度序列是什么意思,但是因为我有 29 个特征,所以我也尝试了 (None,29)(1,29) 并得到了类似的错误。

我对一维卷积的作用有什么误解吗?

这是我期望 Conv1D 在给定 7x1 输入的情况下使用大小为 3 的内核执行的操作的直观描述。

[x][x][x][ ][ ][ ][ ]
[ ][x][x][x][ ][ ][ ]
[ ][ ][x][x][x][ ][ ]
[ ][ ][ ][x][x][x][ ]
[ ][ ][ ][ ][x][x][x]

为什么 Keras 需要 3 个维度?

The three dimensions are (batch_size, feature_size, channels).

定义一维卷积层

Conv1D(32, (3), activation='relu' , input_shape=( 29, 1 ))

将 (4000, 29, 1) 个样本馈送到该层。

简单示例:

from keras import models, layers
import numpy as np

x = np.ones((10, 29, 1))
y = np.zeros((10,))
model = models.Sequential()
model.add(layers.Conv1D(32, (3), activation='relu' , input_shape=( 29,1)))
model.add(layers.Flatten())
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer= "adam", metrics=['accuracy'])
print(model.summary())
model.fit(x,y)