How to perform a 1D convolution in python ?

Published: September 13, 2021

Tags: Python; Numpy; Scipy;

DMCA.com Protection Status

Examples of how to perform a 1D convolution in python:

see also how to convolve two 2-dimensional matrices in python with scipy

1d convolution in python

Let's consider the following data:

F = [1, 2, 3]
G = [0, 1, 0.5]

To compute the 1d convolution between F and G: F*G, a solution is to use numpy.convolve:

C = np.convolve(F,G)

will gives here

array([0. , 1. , 2.5, 4. , 1.5])

Short explanation on how to get the result above. First the kernel G is reversed [0, 1, 0.5] -> [0.5, 1, 0.]

(Step 1) Calculate C[0] => 0.

f g product
- 0.5 -
- 1 -
1 0 0
2 0 0
3 0 0

$$\sum product = 0$$

(Step 2) Calculate C[1] => 1.0

f g product
- 0.5 -
1 1 1
2 0 0
3 0 0

$$\sum product = 1$$

(Step 3) Calculate C[2] => 2.5

f g product
1 0.5 0.5
2 1 2
3 0 0

$$\sum product = 0.5 + 2 = 2.5$$

(Step 4) Calculate C[3] = 4.

f g product
1 0 0
2 0.5 1
3 1.0 3
- 0.0 -

$$\sum product = 1 + 3 = 4$$

(Step 5) Calculate C[4] = 1.5

f g product
1 - 0
2 0 0
3 0.5 1.5
- 1.0 -

$$\sum product = 1.5$$

1d convolution in python using opt "same"

If you want the output the same size as the input F:

np.convolve(F,G,'same')

returns

array([1. , 2.5, 4. ])

1d convolution in python using opt "valid"

np.convolve(F,G,'valid')

returns

array([2.5])

Compute only:

f g product
1 0.5 0.5
2 1 2
3 0 0

$$\sum product = 0.5 + 2 = 2.5$$

Another example

Another example, let's create a rectangular function in python (see also wikipedia's article Convolution)

import numpy as np

def f(x):
        if np.absolute(x) > 0.5:
                y = 0
        else:
                y = 1
        return y

X = np.linspace(-2.0, 2.0, num=100)

F = [f(x) for x in X]

And let's compute for example the autocorrelation

G = [f(x) for x in X]

C = np.convolve(F, G)

To visualize the results, we can first plot the rectangular function using matplotlib:

import matplotlib.pyplot as plt

plt.plot(X,F)

plt.title("How to perform a 1D convolution in python ?")

plt.savefig("1d_convolution_01.png", bbox_inches='tight', dpi=100)

plt.show()

gives

How to perform a 1D convolution in python ?
How to perform a 1D convolution in python ?

and then plot the autocorrelation:

plt.plot(C)

plt.title("How to perform a 1D convolution in python ?")

plt.savefig("1d_convolution_02.png", bbox_inches='tight', dpi=100)

plt.show()

gives here

How to perform a 1D convolution in python ?
How to perform a 1D convolution in python ?

References

Image

of