TensorFlow Conv1D核尺寸维度错误:一维卷积维度不足问题咨询
Hey, let's break down why you're hitting that dimension error and fix it right away!
The Root Cause
Your input shaping is flipped for how tf.layers.conv1d works. Let's look at your code:
inputs_ = tf.placeholder(tf.float32 ,(None, 45), name='inputs') x1 = tf.expand_dims(inputs_, axis=1) # Results in shape (None, 1, 45)
tf.layers.conv1d expects inputs in the format [batch_size, sequence_length, num_features] — and it performs convolution along the sequence_length dimension (the second axis here).
When you set kernel_size=1, the sequence length (1) was just enough to fit the kernel. But bumping it to 3 means you're trying to slide a 3-length kernel over a 1-length sequence — which is physically impossible, hence the dimension error.
The Fix
Adjust the axis you use for expand_dims to move the feature dimension to the end, making your sequence length 45 instead of 1:
inputs_ = tf.placeholder(tf.float32 ,(None, 45), name='inputs') x1 = tf.expand_dims(inputs_, axis=-1) # Now shape is (None, 45, 1) x1 = tf.layers.conv1d(x1, filters=64, kernel_size=3, strides=1, padding='valid')
This gives the convolution kernel enough space (45 units) to slide over, using your 3-sized kernel as intended.
Bonus: Padding Options
- With
padding='valid', your output sequence length will be45 - 3 + 1 = 43(shape:(None, 43, 64)), since the kernel only slides over valid positions without padding. - If you want the output sequence length to match the input (45), switch to
padding='same'— TensorFlow will automatically add zero-padding to the ends of your sequence so the kernel can cover every input position.
内容的提问来源于stack exchange,提问作者bmbigbang

