tensorflowconv-neural-networkconvolution

tensorflow convolve two 1D signals


I have two arrays and I can't figure out how to simply convolve them in tensorflow. In numpy I would do:

import numpy as np
from numpy import convolve

a=np.array([1,0,3])
b=np.array([-1,2])
convolve(a,b)

and the output is array([-1, 2, -3, 6]).

How can I do this in tensorflow? I tried this:

a=tf.constant([1,0,3])
b=tf.constant([-1,2])


tf.nn.convolution(a,b,strides=1)

But I get ValueError: `num_spatial_dims` must be 1, 2, or 3. Received: num_spatial_dims=-1.


Solution

  • Tensorflow does not have a full padding option like in numpy, so you'll have to add padding yourself:

    a=tf.constant([1,0,3])
    b=tf.constant([-1,2])
    b=tf.reverse(b,axis=[0])
    pad_add = len(b)-1
    
    paddings = tf.constant([[pad_add,pad_add]])
    a = tf.pad(a,paddings)
    
    a=tf.reshape(a,(1,len(a),1))
    
    b=tf.reshape(b,(len(b),1,1))
    
    output =tf.nn.convolution(input = a, filters = b)
    print(output.numpy().flatten())
    

    This gives:[-1 2 -3 6]