numpy.correlate()
方法计算两个一维序列的互相关。
示例
import numpy as np
# create two arrays
array1 = np.array([0, 1, 2, 3])
array2 = np.array([2, 0, 1, 3])
# calculate the correlation of two arrays
corr = np.correlate(array1, array2)
print(corr)
# Output: [11]
correlate() 语法
numpy.correlate()
方法的语法是
numpy.correlate(a, v, mode = 'valid')
correlate() 参数
numpy.correlate()
方法接受以下参数
a
,v
- 需要计算相关性的数组(可以是array_like
)mode
(可选) - 指定输出的大小('valid'
、'full'
或'same'
)
correlate() 返回值
numpy.correlate()
方法返回 a
和 v
的离散互相关。
示例 1:查找两个 ndArrays 之间的相关性
在计算两个 ndarrays
之间的相关性时,相关性可以有三种模式。
'valid'
(默认): 输出仅包含有效的互相关值。它返回一个长度为max(M, N) - min(M, N) + 1
的数组,其中 M 和 N 分别是输入数组a
和v
的长度。
'full'
: 输出是输入的完整离散线性互相关。它返回一个长度为M + N - 1
的数组,其中 M 和 N 分别是输入数组a
和v
的长度。
'same'
: 输出的大小与a
相同,相对于'full'
输出进行居中。
让我们看一个例子。
import numpy as np
# create two arrays
array1 = np.array([0, 1, 2, 3])
array2 = np.array([2, 0, 1, 3])
# calculate the valid correlation of two arrays
valid_corr = np.correlate(array1, array2, mode = 'valid')
# calculate the full correlation of two arrays
full_corr = np.correlate(array1, array2, mode = 'full')
# calculate the correlation of two arrays
same_corr = np.correlate(array1, array2, mode = 'same')
print('Correlation in Valid mode :', valid_corr)
print('Correlation in Full mode :', full_corr)
print('Correlation in Same mode :', same_corr)
输出
Correlation in Valid mode : [11] Correlation in Full mode : [ 0 3 7 11 5 4 6] Correlation in Same mode : [ 3 7 11 5]
示例 2:复杂 ndArrays 之间的相关性
numpy.correlate()
函数也可用于查找复杂数据类型之间的相关性。
import numpy as np
# create two arrays of complex numbers
array1 = np.array([1+1j, 2, 3-1j])
array2 = np.array([2, 1-1j, 3+1j])
# calculate the correlation of the complex arrays
corr = np.correlate(array1, array2)
print(corr)
输出
[12.-2.j]