我在Python中使用TensorFlow,正在制作一个具有一维数组作为输入的神经网络。我想在网络中添加一个卷积层,但似乎无法使其正常工作。

我的训练数据如下所示:

n_samples = 20
length_feature = 10
features = np.random.random((n_samples, length_feature))
labels = np.array([1 if sum(e)>5 else 0 for e in features])


如果我建立这样的神经网络

model = keras.Sequential([
    keras.layers.Dense(10, activation='relu', input_shape=(length_feature, )),
    keras.layers.Dense(2, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

history = model.fit(features, labels, batch_size=5, validation_split = 0.2, epochs=10)


这很好用。但是如果我添加像这样的卷积层

model = keras.Sequential([
    keras.layers.Dense(10, activation='relu', input_shape=(length_feature, )),
    keras.layers.Conv1D(kernel_size = 3, filters = 2),
    keras.layers.Dense(2, activation='softmax')
])


然后我得到了错误

ValueError: Input 0 of layer conv1d_4 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 10]


如何为我的神经网络添加卷积层?

最佳答案

Conv1D需要3D输出(batch_sizewidthchannels)。但是密集层会产生2D输出。只需将模型更改为以下内容,

model = keras.Sequential([
    keras.layers.Dense(10, activation='relu', input_shape=(length_feature, )),
    keras.layers.Lambda(lambda x: K.expand_dims(x, axis=-1))
    keras.layers.Conv1D(kernel_size = 3, filters = 2),
    keras.layers.Dense(2, activation='softmax')
])


其中Kkeras.backendtf.keras.backend取决于您用来获取图层的位置。

关于python - TensorFlow:如何为表格(1-D)要素使用卷积层?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59756806/

10-13 04:35