0
0
NumPydata~5 mins

Correlation with np.correlate() in NumPy

Choose your learning style9 modes available
Introduction

We use correlation to find how two sets of numbers relate to each other. np.correlate() helps us measure this relationship by sliding one set over the other and checking how similar they are.

To compare two time series data to see if they move together.
To find repeating patterns in signals like sound or sensor data.
To check similarity between two sequences in data analysis.
To detect delays or shifts between two related datasets.
Syntax
NumPy
np.correlate(a, v, mode='valid')

a and v are the input arrays you want to compare.

mode controls the size of the output: 'valid' returns only points where arrays fully overlap, 'full' returns all overlaps, and 'same' returns output the same size as a.

Examples
Computes correlation where the second array fully fits inside the first.
NumPy
np.correlate([1, 2, 3], [0, 1, 0.5], mode='valid')
Computes correlation at all possible overlaps, including partial ones.
NumPy
np.correlate([1, 2, 3], [0, 1, 0.5], mode='full')
Returns correlation output with the same length as the first array.
NumPy
np.correlate([1, 2, 3], [0, 1, 0.5], mode='same')
Sample Program

This code compares two arrays using np.correlate() with different modes to show how the output changes.

NumPy
import numpy as np

a = np.array([1, 2, 3, 4])
v = np.array([0, 1, 0.5])

result_valid = np.correlate(a, v, mode='valid')
result_full = np.correlate(a, v, mode='full')
result_same = np.correlate(a, v, mode='same')

print('Valid mode:', result_valid)
print('Full mode:', result_full)
print('Same mode:', result_same)
OutputSuccess
Important Notes

np.correlate() is similar to convolution but without flipping the second array.

Correlation values can help find how much one sequence matches another at different shifts.

Use mode='full' to see all possible overlaps, which is useful for pattern detection.

Summary

Correlation measures similarity between two sequences.

np.correlate() slides one array over another and calculates overlap sums.

Different mode options control the size and detail of the output.