【问题标题】:Python - generate array of specific autocorrelationPython - 生成特定自相关数组
【发布时间】:2015-11-24 16:17:47
【问题描述】:

我有兴趣生成一个长度为 N 的数组(或 numpy 系列),该数组将在滞后 1 处表现出特定的自相关。理想情况下,我还想指定均值和方差,并从 (multi) 中提取数据正态分布。但最重要的是,我想指定自相关。我如何使用 numpy 或 scikit-learn 做到这一点?

为了明确和准确,这是我要控制的自相关:

numpy.corrcoef(x[0:len(x) - 1], x[1:])[0][1]

【问题讨论】:

  • “特定自相关”到底是什么意思?是否有您感兴趣的特定时滞?显然,任何信号都可以保证在零延迟时与自身完全相关。
  • 我对 lag=1 感兴趣,请参阅原始问题的编辑。
  • 如果系数接近于零,N 不是太大,你总是做 corrcoef(x[:-1],x[1:]) 那么你可能会生成一个随机数组蛮力。更科学地说,我认为反向 fft 应该能够生成具有特定自相关的数组,但我从来没有这样做过,也没有研究过如何!
  • 您是否关心超过滞后 1 的相关性,即它们是否可以不为零?
  • 我不在乎他们。

标签: python numpy random scikit-learn correlation


【解决方案1】:

如果您只对滞后一阶的自相关感兴趣,您可以生成一阶的auto-regressive process,其参数等于所需的自相关; Wikipedia page上提到了这个属性,但是不难证明。

这里是一些示例代码:

import numpy as np

def sample_signal(n_samples, corr, mu=0, sigma=1):
    assert 0 < corr < 1, "Auto-correlation must be between 0 and 1"

    # Find out the offset `c` and the std of the white noise `sigma_e`
    # that produce a signal with the desired mean and variance.
    # See https://en.wikipedia.org/wiki/Autoregressive_model
    # under section "Example: An AR(1) process".
    c = mu * (1 - corr)
    sigma_e = np.sqrt((sigma ** 2) * (1 - corr ** 2))

    # Sample the auto-regressive process.
    signal = [c + np.random.normal(0, sigma_e)]
    for _ in range(1, n_samples):
        signal.append(c + corr * signal[-1] + np.random.normal(0, sigma_e))

    return np.array(signal)

def compute_corr_lag_1(signal):
    return np.corrcoef(signal[:-1], signal[1:])[0][1]

# Examples.
print(compute_corr_lag_1(sample_signal(5000, 0.5)))
print(np.mean(sample_signal(5000, 0.5, mu=2)))
print(np.std(sample_signal(5000, 0.5, sigma=3)))

corr 参数可让您在滞后 1 处设置所需的自相关,而可选参数 musigma 可让您控制生成信号的均值和标准差。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-02
    • 2013-04-08
    • 2010-12-15
    • 2023-01-13
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 2020-03-24
    相关资源
    最近更新 更多