當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python SciPy signal.correlate用法及代碼示例

本文簡要介紹 python 語言中 scipy.signal.correlate 的用法。

用法:

scipy.signal.correlate(in1, in2, mode='full', method='auto')#

Cross-correlate 兩個 N 維數組。

Cross-correlate in1 和 in2,輸出大小由 mode 參數確定。

參數

in1 array_like

第一個輸入。

in2 array_like

第二輸入。應該具有與 in1 相同的維數。

mode str {‘full’, ‘valid’, ‘same’},可選

指示輸出大小的字符串:

full

輸出是輸入的完全離散線性互相關。 (默認)

valid

輸出僅包含那些不依賴零填充的元素。在 ‘valid’ 模式中,in1 或 in2 在每個維度上都必須至少與另一個一樣大。

same

輸出與 in1 大小相同,以 ‘full’ 輸出為中心。

method str {‘auto’, ‘direct’, ‘fft’},可選

一個字符串,指示使用哪種方法來計算相關性。

direct

相關性由總和(相關性的定義)直接確定。

fft

快速傅立葉變換用於更快地執行相關(僅適用於數值數組。)

auto

根據更快的估計自動選擇直接或傅立葉方法(默認)。有關詳細信息,請參閱 convolve 注釋。

返回

correlate 數組

一個 N 維數組,包含 in1 與 in2 的離散線性互相關的子集。

注意

兩個d-dimensional 數組 x 和 y 的相關性 z 定義為:

z[...,k,...] = sum[..., i_l, ...] x[..., i_l,...] * conj(y[..., i_l - k,...])

這樣,如果 x 和 y 是一維數組並且 z = correlate(x, y, 'full') 那麽

對於

其中 x 的長度,當 m 超出 y 範圍時, 為 0。

method='fft' 僅適用於數值數組,因為它依賴於 fftconvolve 。在某些情況下(即對象數組或舍入整數可能會丟失精度),始終使用method='direct'

當使用帶有偶數長度輸入的 “same” 模式時,correlate correlate2d 的輸出不同:它們之間存在 1 索引偏移。

例子

使用互相關實現匹配濾波器,以恢複通過噪聲通道的信號。

>>> import numpy as np
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> rng = np.random.default_rng()
>>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128)
>>> sig_noise = sig + rng.standard_normal(len(sig))
>>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128
>>> clock = np.arange(64, len(sig), 128)
>>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True)
>>> ax_orig.plot(sig)
>>> ax_orig.plot(clock, sig[clock], 'ro')
>>> ax_orig.set_title('Original signal')
>>> ax_noise.plot(sig_noise)
>>> ax_noise.set_title('Signal with noise')
>>> ax_corr.plot(corr)
>>> ax_corr.plot(clock, corr[clock], 'ro')
>>> ax_corr.axhline(0.5, ls=':')
>>> ax_corr.set_title('Cross-correlated with rectangular pulse')
>>> ax_orig.margins(0, 0.1)
>>> fig.tight_layout()
>>> plt.show()
scipy-signal-correlate-1_00_00.png

計算噪聲信號與原始信號的互相關。

>>> x = np.arange(128) / 128
>>> sig = np.sin(2 * np.pi * x)
>>> sig_noise = sig + rng.standard_normal(len(sig))
>>> corr = signal.correlate(sig_noise, sig)
>>> lags = signal.correlation_lags(len(sig), len(sig_noise))
>>> corr /= np.max(corr)
>>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, figsize=(4.8, 4.8))
>>> ax_orig.plot(sig)
>>> ax_orig.set_title('Original signal')
>>> ax_orig.set_xlabel('Sample Number')
>>> ax_noise.plot(sig_noise)
>>> ax_noise.set_title('Signal with noise')
>>> ax_noise.set_xlabel('Sample Number')
>>> ax_corr.plot(lags, corr)
>>> ax_corr.set_title('Cross-correlated signal')
>>> ax_corr.set_xlabel('Lag')
>>> ax_orig.margins(0, 0.1)
>>> ax_noise.margins(0, 0.1)
>>> ax_corr.margins(0, 0.1)
>>> fig.tight_layout()
>>> plt.show()
scipy-signal-correlate-1_01_00.png

相關用法


注:本文由純淨天空篩選整理自scipy.org大神的英文原創作品 scipy.signal.correlate。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。