Understand TensorFlow tf.layers.conv1d() with Examples – TensorFlow Tutorial

By | March 3, 2022

tf.layers.conv1d() can build a 1D convolution layer easily. In this tutorial, we will use some examples to show you how to use this function correctly.

tf.layers.conv1d()

This function is defined as:

def conv1d(inputs,
           filters,
           kernel_size,
           strides=1,
           padding='valid',
           data_format='channels_last',
           dilation_rate=1,
           activation=None,
           use_bias=True,
           kernel_initializer=None,
           bias_initializer=init_ops.zeros_initializer(),
           kernel_regularizer=None,
           bias_regularizer=None,
           activity_regularizer=None,
           kernel_constraint=None,
           bias_constraint=None,
           trainable=True,
           name=None,
           reuse=None):

As to this function, there are some important parameters we should notice:

inputs: input tensor, the shape of it usually should be [batch_size, time_len, feature_dim]

filters: integer, the dimensionality of the output space.

kernel_size: integer or tuple/list of a single integer, specifying the length of the 1D convolution window

strides: integer or tuple/list of a single integer, specifying the stride length of the convolution

padding: same or valid.

This function will return a tensor with shape [batch_size, width, filters], width is computed based on kernel_size, strides and padding.

To understand more about these parameters, you can view:

Understand tf.layers.conv2d() with Examples – TensorFlow Tutorial

How to use tf.layers.conv1d()?

We will use some examples to show you how to use.

Example 1 :

import tensorflow as tf
import numpy as np
inputs = tf.Variable(tf.truncated_normal([3, 15, 10], stddev=0.1), name="inputs")
x = tf.layers.conv1d(inputs, filters = 32, kernel_size = 5, use_bias = True, padding = 'same')

init = tf.global_variables_initializer()
init_local = tf.local_variables_initializer()
with tf.Session() as sess:
    sess.run([init, init_local])
    np.set_printoptions(precision=4, suppress=True)
    a =sess.run(x)
    print(a.shape)

In this example, the filters = 32, it means the last dim of result is 32. padding = ‘same’ means the second axis is also 15.

Run this code, we will get:

(3, 15, 32)

Example 2:

If kernel_size = 4, padding = ‘valid’.

x = tf.layers.conv1d(inputs, filters = 32, kernel_size = 4, use_bias = True, padding = 'valid')

We will get: (3, 12, 32)

Leave a Reply