0
0
NumPydata~5 mins

Convolution with np.convolve() in NumPy

Choose your learning style9 modes available
Introduction

Convolution helps combine two sets of data to see how one affects the other over time or space.

To smooth noisy data by blending it with a small averaging window.
To detect patterns or features in signals like sound or images.
To apply filters in image processing, like blurring or sharpening.
To analyze how one signal changes when passed through a system.
To combine two time series to see their combined effect.
Syntax
NumPy
np.convolve(a, v, mode='full')

a and v are the input arrays to combine.

mode controls the size of the output: 'full', 'same', or 'valid'.

Examples
Combines two arrays fully, showing all overlaps.
NumPy
np.convolve([1, 2, 3], [0, 1, 0.5], mode='full')
Returns output the same size as the first array.
NumPy
np.convolve([1, 2, 3], [0, 1, 0.5], mode='same')
Returns only parts where arrays fully overlap.
NumPy
np.convolve([1, 2, 3], [0, 1, 0.5], mode='valid')
Sample Program

This code shows how to combine a signal with a kernel using convolution in three ways. It prints the results so you can see the differences.

NumPy
import numpy as np

# Two simple arrays
signal = np.array([1, 2, 3, 4])
kernel = np.array([0, 1, 0.5])

# Full convolution
result_full = np.convolve(signal, kernel, mode='full')

# Same size as signal
result_same = np.convolve(signal, kernel, mode='same')

# Only valid overlaps
result_valid = np.convolve(signal, kernel, mode='valid')

print('Full convolution:', result_full)
print('Same size output:', result_same)
print('Valid convolution:', result_valid)
OutputSuccess
Important Notes

Convolution flips one array before sliding it over the other.

The mode parameter changes the output length and what parts are included.

Use convolution to apply filters or combine signals in many fields like audio, image, and data analysis.

Summary

Convolution combines two arrays to analyze how one affects the other.

Use np.convolve() with different modes to control output size.

It is useful for smoothing, filtering, and pattern detection in data.