NumPy convolve()
The numpy.convolve()
function computes the discrete, linear convolution of two one-dimensional sequences.
Convolution is commonly used in signal processing to model the effect of a linear time-invariant system on a signal.
Syntax
</>
Copy
numpy.convolve(a, v, mode='full')
Parameters
Parameter | Type | Description |
---|---|---|
a | (N,) array_like | First one-dimensional input array. |
v | (M,) array_like | Second one-dimensional input array. |
mode | {‘full’, ‘valid’, ‘same’}, optional | Determines the size of the output array. |
Modes in Convolution
Mode | Description |
---|---|
'full' | Returns the convolution at each point of overlap with an output size of (N+M-1). Includes boundary effects. |
'same' | Returns an output of length max(N, M), keeping the center of the convolution. |
'valid' | Returns only values where the input arrays fully overlap, with an output size of max(N, M) – min(N, M) + 1. |
Return Value
Returns an ndarray containing the discrete, linear convolution of the input arrays.
Examples
1. Basic Convolution Using Default Mode (‘full’)
In this example, we perform a simple convolution using two one-dimensional arrays.
</>
Copy
import numpy as np
# Define two input sequences
a = np.array([1, 2, 3])
v = np.array([0, 1, 0.5])
# Compute the convolution using default mode ('full')
result = np.convolve(a, v)
# Print the result
print("Convolution result (full mode):", result)
Output:
Convolution result (full mode): [0. 1. 2.5 4. 1.5]

2. Convolution Using ‘same’ Mode
The ‘same’ mode ensures that the output has the same length as the longer input sequence.
</>
Copy
import numpy as np
# Define two input sequences
a = np.array([1, 2, 3])
v = np.array([0, 1, 0.5])
# Compute the convolution using 'same' mode
result = np.convolve(a, v, mode='same')
# Print the result
print("Convolution result (same mode):", result)
Output:
Convolution result (same mode): [1. 2.5 4. ]

3. Convolution Using ‘valid’ Mode
The ‘valid’ mode returns only the parts of the convolution where the input arrays fully overlap.
</>
Copy
import numpy as np
# Define two input sequences
a = np.array([1, 2, 3])
v = np.array([0, 1, 0.5])
# Compute the convolution using 'valid' mode
result = np.convolve(a, v, mode='valid')
# Print the result
print("Convolution result (valid mode):", result)
Output:
Convolution result (valid mode): [2.5]

4. Convolution with a Larger Kernel
This example demonstrates the convolution of a sequence with a larger kernel.
</>
Copy
import numpy as np
# Define a longer input sequence
a = np.array([3, 2, 1, 5, 4])
# Define a kernel
v = np.array([0.2, 0.5, 0.2])
# Compute the convolution using 'full' mode
result = np.convolve(a, v, mode='full')
# Print the result
print("Convolution result with larger kernel:", result)
Output:
Convolution result with larger kernel: [0.6 1.9 1.8 1.9 3.5 3. 0.8]

The result shows how the input sequence is smoothed when convolved with a larger kernel.