我有兴趣生成一个长度为 N 的数组(或 numpy 系列),它将在滞后 1 处表现出特定的自相关性。理想情况下,我还想指定均值和方差,并从(多)正态分布中提取数据。但最重要的是,我想指定自相关。如何使用 numpy 或 scikit-learn 执行此操作?
为了明确和精确,这是我想要控制的自相关:
numpy.corrcoef(x[0:len(x) - 1], x[1:])[0][1]
如果您只对滞后一处的自相关感兴趣,则可以生成自回归过程 https://en.wikipedia.org/wiki/Autocorrelation一阶,参数等于所需的自相关;该属性在维基百科页面 https://en.wikipedia.org/wiki/Autoregressive_model#Yule.E2.80.93Walker_equations,但证明这一点并不难。
这是一些示例代码:
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
让您设置所需的滞后一自相关和可选参数,mu
and sigma
,让您控制生成信号的平均值和标准偏差。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)