为什么在尝试 运行 Conv1D 层时会出现 Conv2D 错误?

Why do I get a Conv2D error trying to run Conv1D layer?

我正在尝试编写一个带有回归(一维浮点)输出的简单一维卷积。

model = Sequential()
model.add(Conv1D(filters=1, kernel_size=8, activation='relu'))
model.add(Dense(1, 'softmax'))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(x = x_train, y = y_train, epochs=3)

这给了我错误:

TypeError: Exception encountered when calling layer "conv1d" (type Conv1D).
Input 'filter' of 'Conv2D' Op has type float32 that does not match type int32 of argument 'input'.
Call arguments received:
• inputs=tf.Tensor(shape=(None, 30931, 4), dtype=int32)

即使我的代码是错误的,我怎么可能在没有 Conv2D 层的情况下收到 Conv2D 错误?

x_train 是一个包含 3361 个训练示例的 numpy 数组,每个一维数组的长度为 30931,具有 4 个通道的 np.int32 数据。形状 = (3361,30931, 4)

y_train 是一个包含 3361 个 np.float64 值的 numpy 数组,我正在训练我的网络来识别它。

这种输入数据格式应该有效吗?还是我需要转换它或使用其他数据类型?

我的 Conv1D 层中是否需要 input_shape 参数?如果可以,应该是什么?

我意识到这过于简单化了,并计划了一个更复杂的网络来针对更多示例进行训练,但只想先 运行。

您的 x_train 数据应为 float 数据类型。此外,您通常会将 2D 数据展平为 1D 或应用一些全局池化操作,然后再将其输入 softmax 输出层:

import tensorflow as tf

x_train = tf.random.normal((10,30931, 4), dtype=tf.float32)
y_train = tf.random.uniform((10,), maxval=2, dtype=tf.int32)
y_train = tf.keras.utils.to_categorical(y_train, 2)

model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv1D(filters=1, kernel_size=8, activation='relu'))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(2, 'softmax'))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(x = x_train, y = y_train, epochs=3)

关于您的错误信息,Conv1DConv2D层都使用了tf.nn.convolution操作internally。有趣的是,问题是由参数 filter 引起的,它具有 float 数据类型,无法处理整数输入。