Skip to content
Advertisement

how to perform a backwards correlation/convolution in python

I am trying to perform a backwards correlation (at least that’s what I think it’s called) on 2 matrices to get a resultant matrix.

Note: backwards convolution works too, because I’m applying this to a CNN.

I have the following two matrices:

vals:

JavaScript

w0:

JavaScript

I essentially want to apply a sliding window, except in this case all the values of w0 are multiplied by the scalar value at each point in vals, then added with adjacent values.

Assuming a stride of 1 and a padding of same (wrt vals), the following code gives the result I want:

JavaScript

Resulting in:

JavaScript

Which I would then shrink to exclude the padding, so:

JavaScript

Either of the two results for concat would be fine, but preferably the one that includes the padding.

Does anyone know of a way to do this without using python loops? I’d prefer to use numpy or some other library as it is bound to perform the same calculation faster than my code.

EDIT:

I also want to perform the same kind of backward correlation on w0, so using vals again but instead using:

a:

JavaScript

And in this case taking a 3×3 sliding window along a with a padding of 1, and multiply all values in the sliding window by the associated index of the scalar value in vals, and finally getting an output the same size as w0. The following code achieves this:

JavaScript

with:

JavaScript

Advertisement

Answer

scipy.signal‘s convolve is actually what you want:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement