码迷,mamicode.com
首页 > 其他好文 > 详细

机器学习(1)互相关

时间:2019-07-07 16:03:46      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:check   ros   real   turn   port   between   assert   after   win   

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

机器学习(1)互相关

标签:check   ros   real   turn   port   between   assert   after   win   

原文地址:https://www.cnblogs.com/linengier/p/11146476.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!