gpt4 book ai didi

python - 一维卷积层尺寸不匹配问题

转载 作者:行者123 更新时间:2023-12-05 05:56:02 24 4
gpt4 key购买 nike

我正在尝试了解卷积层在神经网络中的工作原理。我针对类似问题找到了两个不同的相关帖子并尝试了这些建议,但无法解决。

  1. Keras dimensionality in convolutional layer mismatch
  2. ValueError: Input 0 is incompatible with layer conv_1: expected ndim=3, found ndim=4
import tensorflow as tf
model_valid = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(10,)),
tf.keras.layers.Dense(16, activation='relu'),
tf.keras.layers.Conv1D(16, kernel_size=(2), activation='relu', padding='same'),
tf.keras.layers.MaxPooling1D(pool_size=(4), strides=3, padding='valid'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(1, activation='softmax')
])
model_valid.summary()

我收到一个不兼容问题,因为层 conv1d_37 的输入 0 与该层不兼容:预期 ndim=3,发现 ndim=2。收到的完整形状:[无,16]。构建卷积层时会出现问题。

最佳答案

第一个 Conv1D 之前的输入形状不正确。正如用户 spb 所建议的那样,Conv1D 的输入必须是 3D 张量,尽管移除展平层(如建议的那样)不会解决问题。

相反,只需在第一个 Dense 层之后添加一个额外的维度。

import tensorflow as tf
model_valid = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(10,)),
tf.keras.layers.Dense(16, activation='relu'),
tf.keras.layers.Reshape((16, 1)), # ADD THIS LINE OF CODE
tf.keras.layers.Conv1D(16, kernel_size=(2), activation='relu', padding='same'),
tf.keras.layers.MaxPooling1D(pool_size=(4), strides=3, padding='valid'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(1, activation='softmax')
])
model_valid.summary()

现在模型总结是:

Model: "sequential_2"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
flatten_4 (Flatten) (None, 10) 0
_________________________________________________________________
dense_4 (Dense) (None, 16) 176
_________________________________________________________________
reshape (Reshape) (None, 16, 1) 0
_________________________________________________________________
conv1d_1 (Conv1D) (None, 16, 16) 48
_________________________________________________________________
max_pooling1d (MaxPooling1D) (None, 5, 16) 0
_________________________________________________________________
flatten_5 (Flatten) (None, 80) 0
_________________________________________________________________
dense_5 (Dense) (None, 1) 81
=================================================================
Total params: 305
Trainable params: 305
Non-trainable params: 0
_________________________________________________________________

关于python - 一维卷积层尺寸不匹配问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69305003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com