代码之家  ›  专栏  ›  技术社区  ›  Ben

如何使用numpy.correlate进行自相关?

  •  81
  • Ben  · 技术社区  · 17 年前

    我尝试过使用numpy的相关函数,但我不相信结果,因为它几乎总是给出第一个数字所在的向量 应该是最大的。

    所以,这个问题实际上是两个问题:

    1. 到底是什么 numpy.correlate 做什么?
    2. 如何使用它(或其他东西)进行自相关?
    12 回复  |  直到 7 年前
        1
  •  129
  •   bkanuka    11 年前

    要回答你的第一个问题, numpy.correlate(a, v, mode) 正在执行 a 与…相反 v 并给出按指定模式剪裁的结果。这个 definition of convolution ,C(t)= -<我< v t+i

    • “full”模式返回每个 t 两者都在哪里 和 有一些重叠。
    • “相同”模式返回与最短向量长度相同的结果( A. v ).
    • “有效”模式仅在以下情况下返回结果 A. 完全重叠。这个 documentation 对于 numpy.convolve 提供有关模式的更多详细信息。

    numpy.correlate 是 给你自相关,它只是给你多一点。自相关用于发现信号或函数在某个时差下与自身的相似程度。当时差为0时,自相关应该是最高的,因为信号本身是相同的,所以您希望自相关结果数组中的第一个元素是最大的。但是,相关性不是在时间差为0时开始的。它从负时差开始,接近0,然后变为正。也就是说,您期望:

    -<我< A. 我 t+i 其中0<=t<

    自相关(a)= -<我< 我 v t+i 其中-<t<

    def autocorr(x):
        result = numpy.correlate(x, x, mode='full')
        return result[result.size/2:]
    

    当然,您需要进行错误检查以确保 x These pages 关于自相关的知识非常有用,如果你不介意涉猎符号和沉重的概念,可以给你更好的理论背景。

        2
  •  33
  •   jdow    7 年前

    自相关有两种版本:统计和卷积。除了一点细节外,它们的作用是相同的:统计版本标准化为区间[-1,1]。下面是一个如何进行统计分析的示例:

    def acf(x, length=20):
        return numpy.array([1]+[numpy.corrcoef(x[:-i], x[i:])[0,1]  \
            for i in range(1, length)])
    
        3
  •  25
  •   Jason    8 年前

    我认为有两件事会让这个话题更加混乱:

    我已经创建了5个函数来计算一维数组的自相关,带有部分v.s.非部分区分。有些使用统计公式,有些使用信号处理意义上的相关,这也可以通过FFT实现。但所有结果都是自相关的 统计数字 定义,所以它们说明了它们是如何相互关联的。代码如下:

    import numpy
    import matplotlib.pyplot as plt
    
    def autocorr1(x,lags):
        '''numpy.corrcoef, partial'''
    
        corr=[1. if l==0 else numpy.corrcoef(x[l:],x[:-l])[0][1] for l in lags]
        return numpy.array(corr)
    
    def autocorr2(x,lags):
        '''manualy compute, non partial'''
    
        mean=numpy.mean(x)
        var=numpy.var(x)
        xp=x-mean
        corr=[1. if l==0 else numpy.sum(xp[l:]*xp[:-l])/len(x)/var for l in lags]
    
        return numpy.array(corr)
    
    def autocorr3(x,lags):
        '''fft, pad 0s, non partial'''
    
        n=len(x)
        # pad 0s to 2n-1
        ext_size=2*n-1
        # nearest power of 2
        fsize=2**numpy.ceil(numpy.log2(ext_size)).astype('int')
    
        xp=x-numpy.mean(x)
        var=numpy.var(x)
    
        # do fft and ifft
        cf=numpy.fft.fft(xp,fsize)
        sf=cf.conjugate()*cf
        corr=numpy.fft.ifft(sf).real
        corr=corr/var/n
    
        return corr[:len(lags)]
    
    def autocorr4(x,lags):
        '''fft, don't pad 0s, non partial'''
        mean=x.mean()
        var=numpy.var(x)
        xp=x-mean
    
        cf=numpy.fft.fft(xp)
        sf=cf.conjugate()*cf
        corr=numpy.fft.ifft(sf).real/var/len(x)
    
        return corr[:len(lags)]
    
    def autocorr5(x,lags):
        '''numpy.correlate, non partial'''
        mean=x.mean()
        var=numpy.var(x)
        xp=x-mean
        corr=numpy.correlate(xp,xp,'full')[len(x)-1:]/var/len(x)
    
        return corr[:len(lags)]
    
    
    if __name__=='__main__':
    
        y=[28,28,26,19,16,24,26,24,24,29,29,27,31,26,38,23,13,14,28,19,19,\
                17,22,2,4,5,7,8,14,14,23]
        y=numpy.array(y).astype('float')
    
        lags=range(15)
        fig,ax=plt.subplots()
    
        for funcii, labelii in zip([autocorr1, autocorr2, autocorr3, autocorr4,
            autocorr5], ['np.corrcoef, partial', 'manual, non-partial',
                'fft, pad 0s, non-partial', 'fft, no padding, non-partial',
                'np.correlate, non-partial']):
    
            cii=funcii(y,lags)
            print(labelii)
            print(cii)
            ax.plot(lags,cii,label=labelii)
    
        ax.set_xlabel('lag')
        ax.set_ylabel('correlation coefficient')
        ax.legend()
        plt.show()
    

    以下是输出图:

    enter image description here

    我们看不到全部5条线,因为其中3条线重叠(在紫色处)。重叠都是非偏自相关。这是因为信号处理方法的计算( np.correlate

    还请注意 fft, no padding, non-partial (红线)结果不同,因为在进行FFT之前,它没有用0填充时间序列,所以它是循环FFT。我无法详细解释原因,这是我从其他地方学到的。

        4
  •  24
  •   Felix    7 年前

    numpy.corrcoef numpy.correlate 要计算t滞后的统计相关性:

    def autocorr(x, t=1):
        return numpy.corrcoef(numpy.array([x[:-t], x[t:]]))
    
        5
  •  12
  •   Community Mohan Dere    9 年前

    由于我刚刚遇到了同样的问题,我想与您分享几行代码。事实上,到目前为止,关于stackoverflow中的自相关的文章已经有好几篇了。如果将自相关定义为 a(x, L) = sum(k=0,N-L-1)((xk-xbar)*(x(k+L)-xbar))/sum(k=0,N-1)((xk-xbar)**2) [这是IDL的a_correlate函数中给出的定义,它与我在问题2的答案中看到的一致 #12269834

    import numpy as np
    import matplotlib.pyplot as plt
    
    # generate some data
    x = np.arange(0.,6.12,0.01)
    y = np.sin(x)
    # y = np.random.uniform(size=300)
    yunbiased = y-np.mean(y)
    ynorm = np.sum(yunbiased**2)
    acor = np.correlate(yunbiased, yunbiased, "same")/ynorm
    # use only second half
    acor = acor[len(acor)/2:]
    
    plt.plot(acor)
    plt.show()
    

    mode="same" 而不是 mode="full" 和其他人一样。

        6
  •  12
  •   Ruggero    10 年前

    您的问题1已经在这里的几个优秀答案中进行了广泛讨论。

    1. 从信号中减去平均值,获得无偏信号

    2. 计算无偏信号的傅里叶变换

    3. 通过取无偏信号的傅里叶变换各值的平方范数,计算信号的功率谱密度

    4. 通过无偏信号的平方和对功率谱密度的傅里叶逆变换进行规范化,只取结果向量的一半

    def autocorrelation (x) :
        """
        Compute the autocorrelation of the signal, based on the properties of the
        power spectral density of the signal.
        """
        xp = x-np.mean(x)
        f = np.fft.fft(xp)
        p = np.array([np.real(v)**2+np.imag(v)**2 for v in f])
        pi = np.fft.ifft(p)
        return np.real(pi)[:x.size/2]/np.sum(xp**2)
    
        7
  •  8
  •   fisherp    7 年前

    numpy.correlate的另一种替代方法在中提供 statsmodels.tsa.stattools.acf() . 这将产生一个连续递减的自相关函数,如OP所述。实现它相当简单:

    from statsmodels.tsa import stattools
    # x = 1-D array
    # Yield normalized autocorrelation function of number lags
    autocorr = stattools.acf( x )
    
    # Get autocorrelation coefficient at lag = 1
    autocorr_coeff = autocorr[1]
    

    nlag= 您的特定应用程序的选项。在这一页的底部有一条引文 statistics behind the function .

        8
  •  2
  •   ascripter    7 年前

    np.correlate 没有做我需要的工作。

    关联 是 平均所有可能的时间点对 在远处。

    def autocross(x, y):
        c = np.correlate(x, y, "same")
        v = [c[i]/( len(x)-abs( i - (len(x)/2)  ) ) for i in range(len(c))]
        return v
    

        9
  •  1
  •   litepresence    10 年前

    我使用talib.CORREL进行如下自相关,我怀疑您可以对其他软件包进行同样的处理:

    def autocorrelate(x, period):
    
        # x is a deep indicator array 
        # period of sample and slices of comparison
    
        # oldest data (period of input array) may be nan; remove it
        x = x[-np.count_nonzero(~np.isnan(x)):]
        # subtract mean to normalize indicator
        x -= np.mean(x)
        # isolate the recent sample to be autocorrelated
        sample = x[-period:]
        # create slices of indicator data
        correls = []
        for n in range((len(x)-1), period, -1):
            alpha = period + n
            slices = (x[-alpha:])[:period]
            # compare each slice to the recent sample
            correls.append(ta.CORREL(slices, sample, period)[-1])
        # fill in zeros for sample overlap period of recent correlations    
        for n in range(period,0,-1):
            correls.append(0)
        # oldest data (autocorrelation period) will be nan; remove it
        correls = np.array(correls[-np.count_nonzero(~np.isnan(correls)):])      
    
        return correls
    
    # CORRELATION OF BEST FIT
    # the highest value correlation    
    max_value = np.max(correls)
    # index of the best correlation
    max_index = np.argmax(correls)
    
        10
  •  1
  •   dignitas    8 年前

    没有熊猫的简单解决方案:

    import numpy as np
    
    def auto_corrcoef(x):
       return np.corrcoef(x[1:-1], x[2:])[0,1]
    
        11
  •  1
  •   Jian    8 年前

    时间是复杂的 N*log(N)

    def autocorr1(x):
        r2=np.fft.ifft(np.abs(np.fft.fft(x))**2).real
        return r2[:len(x)//2]
    

    N*log(N)

    def autocorr2(x):
        r2=np.fft.ifft(np.abs(np.fft.fft(x))**2).real
        c=(r2/x.shape-np.mean(x)**2)/np.std(x)**2
        return c[:len(x)//2]
    

    A.Levy提供的方法是有效的,但我在我的PC上测试了它,它的时间复杂性似乎很高 N*N

    def autocorr(x):
        result = numpy.correlate(x, x, mode='full')
        return result[result.size/2:]
    
        12
  •  0
  •   dbanas    11 年前

    mode : {'valid', 'same', 'full'}, optional
        Refer to the `convolve` docstring.  Note that the default
        is `valid`, unlike `convolve`, which uses `full`.
    

    这意味着,当与无“模式”定义一起使用时,Numpy.correlate函数将返回标量,当为其两个输入参数提供相同的向量时(即-当用于执行自相关时)。

        13
  •  0
  •   Antonio Catalano    8 年前

    绘制给定返回时间序列的统计自相关:

    import matplotlib.pyplot as plt
    
    def plot_autocorr(returns, lags):
        autocorrelation = []
        for lag in range(lags+1):
            corr_lag = returns.corr(returns.shift(-lag)) 
            autocorrelation.append(corr_lag)
        plt.plot(range(lags+1), autocorrelation, '--o')
        plt.xticks(range(lags+1))
        return np.array(autocorrelation)