Understand tf.nn.conv1d(): Compute a 1-D Convolution – TensorFlow Tutorial

By | August 24, 2020

TensorFlow tf.nn.conv1d() allow us to compute a 1-D convolution for a tensor. In this tutorial, we will use some examples to show you how to use this function correctly.

Syntax

tf.nn.conv1d() is defined as:

tf.nn.conv1d(
    value,
    filters,
    stride,
    padding,
    use_cudnn_on_gpu=None,
    data_format=None,
    name=None
)

We should notice: tf.nn.conv1d() is similar to tf.nn.conv2d(), we should notice the difference between them.

Understand tf.nn.conv2d(): Compute a 2-D Convolution in TensorFlow – TensorFlow Tutorial

Parameters

value: the input tensor, the shape of it should be: [batch, in_width, in_channels]. However, the shape of it in tf.nn.conv2d() is: [batch, in_height, in_width, in_channels]

filters: the shape of it should be: [filter_width, in_channels, out_channels]. However, the filters in tf.nn.conv2d() is: [filter_height, filter_width, in_channels, out_channels].

stride: It is an integer, such as 1, 2, 3,….

padding: The type of padding algorithm to use, it is same to tf.nn.conv2d().

data_format: It can be NWC or NCW, default is NWC. It determines the dimension of input and filters.

NWC: It means the value= [batch, in_width, in_channels], filters = [filter_width, in_channels, out_channels]

NCW: It means the value= [batch, in_channels, in_width], filters = [in_channels, filter_width, out_channels]

Return

tf.nn.conv1d() will return a tensor with the shape [batch, out_width, out_channels], however, the tf.nn.conv2d() will return a tensor with the shape [batch, out_height, out_width, out_channels]

Here we will use an example to show you how to use this function.

import tensorflow as tf
#bacth = 1
input = tf.Variable(tf.constant(1.0, shape=[1, 5, 1]))
#out_channels = 1
filter = tf.Variable(tf.constant([-1.0, 0], shape=[2, 1, 1]))
op = tf.nn.conv1d(input, filter, stride=1, padding='SAME')

Here batch = 1, out_channels = 1, the output op will be [1, out_width, 1]

Output op

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print("op:\n",sess.run(op))

Run this code, op will be:

op:
 [[[-1.]
  [-1.]
  [-1.]
  [-1.]
  [-1.]]]

Leave a Reply