使用Python估计自相关 [英] Estimate Autocorrelation using Python

查看:313
本文介绍了使用Python估计自相关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对下面显示的信号执行自相关.两个连续点之间的时间为2.5毫秒(或重复频率为400Hz).

I would like to perform Autocorrelation on the signal shown below. The time between two consecutive points is 2.5ms (or a repetition rate of 400Hz).

这是我想使用的自动相关估计公式(来自 http://en. wikipedia.org/wiki/Autocorrelation ,估算"部分:

This is the equation for estimating autoacrrelation that I would like to use (Taken from http://en.wikipedia.org/wiki/Autocorrelation, section Estimation):

在python中找到我的数据的估计自相关的最简单方法是什么?我可以使用类似于numpy.correlate的东西吗?

What is the simplest method of finding the estimated autocorrelation of my data in python? Is there something similar to numpy.correlate that I can use?

还是我应该计算均值和方差?

Or should I just calculate the mean and variance?

unutbu 的帮助下,我写了:

from numpy import *
import numpy as N
import pylab as P

fn = 'data.txt'
x = loadtxt(fn,unpack=True,usecols=[1])
time = loadtxt(fn,unpack=True,usecols=[0]) 

def estimated_autocorrelation(x):
    n = len(x)
    variance = x.var()
    x = x-x.mean()
    r = N.correlate(x, x, mode = 'full')[-n:]
    #assert N.allclose(r, N.array([(x[:n-k]*x[-(n-k):]).sum() for k in range(n)]))
    result = r/(variance*(N.arange(n, 0, -1)))
    return result

P.plot(time,estimated_autocorrelation(x))
P.xlabel('time (s)')
P.ylabel('autocorrelation')
P.show()

推荐答案

我认为此特定计算没有NumPy函数.这是我的写法:

I don't think there is a NumPy function for this particular calculation. Here is how I would write it:

def estimated_autocorrelation(x):
    """
    http://stackoverflow.com/q/14297012/190597
    http://en.wikipedia.org/wiki/Autocorrelation#Estimation
    """
    n = len(x)
    variance = x.var()
    x = x-x.mean()
    r = np.correlate(x, x, mode = 'full')[-n:]
    assert np.allclose(r, np.array([(x[:n-k]*x[-(n-k):]).sum() for k in range(n)]))
    result = r/(variance*(np.arange(n, 0, -1)))
    return result

assert语句可以检查计算并记录其意图.

The assert statement is there to both check the calculation and to document its intent.

当您确信此功能可以按预期运行时,可以注释掉assert语句,或使用python -O运行脚本. (-O标志告诉Python忽略断言语句.)

When you are confident this function is behaving as expected, you can comment-out the assert statement, or run your script with python -O. (The -O flag tells Python to ignore assert statements.)

这篇关于使用Python估计自相关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆