tensorflow – Using 1D convolution – Basic example

Update: TensorFlow now supports 1D convolution since version r0.11, using tf.nn.conv1d.

Consider a basic example with an input of length 10, and dimension 16. The batch size is 32. We therefore have a placeholder with input shape [batch_size, 10, 16].

batch_size = 32
x = tf.placeholder(tf.float32, [batch_size, 10, 16])

We then create a filter with width 3, and we take 16 channels as input, and output also 16 channels.

filter = tf.zeros([3, 16, 16])  # these should be real values, not 0

Finally we apply tf.nn.conv1d with a stride and a padding:

  • stride: integer s
  • padding: this works like in 2D, you can choose between SAME and VALID. SAME will output the same input length, while VALID will not add zero padding.

For our example we take a stride of 2, and a valid padding.

output = tf.nn.conv1d(x, filter, stride=2, padding="VALID")

The output shape should be [batch_size, 4, 16].
With padding="SAME", we would have had an output shape of [batch_size, 5, 16].

For previous versions of TensorFlow, you can just use 2D convolutions while setting the height of the inputs and the filters to 1.

if you want to reproduce, please indicate the source:
tensorflow – Using 1D convolution – Basic example - CodeDay