机器学习(1)互相关

Computing the cross-correlation function is useful for finding the time-delay offset between two time series.
Python has the numpy.correlate function. But there is a much faster FFT-based implementation.
Check out the following paper for an application of this function:

import numpy as np
from numpy.fft import fft, ifft, fft2, ifft2, fftshift

def cross_correlation_using_fft(x, y):
    f1 = fft(x)
    f2 = fft(np.flipud(y))
    cc = np.real(ifft(f1 * f2))
    return fftshift(cc)

# shift < 0 means that y starts 'shift' time steps before x # shift > 0 means that y starts 'shift' time steps after x
def compute_shift(x, y):
    assert len(x) == len(y)
    c = cross_correlation_using_fft(x, y)
    assert len(c) == len(x)
    zero_index = int(len(x) / 2) - 1
    shift = zero_index - np.argmax(c)
    return shift

We can test the above function by shifting the second series manually and seeing if the shift is accurately computed:

for n in range(1000, 1050, 7):
    for s in range(-5, 5):        
        a = [random.random() for _ in xrange(n)] # big random sequence of values
        b = a
        if s >= 1:
            a = a[s:]
            b = b[:-s]
        elif s <= -1:            
            a = a[:s]
            b = b[-s:]
        assert s_optimal == s

转载于:https://www.cnblogs.com/linengier/p/11146476.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值