我有一个未生成的一维 NumPy 数组。现在,我们将使用生成的一个。
import numpy as np
arr1 = np.random.uniform(0, 100, 1_000)
我需要一个与 0.3
相关的数组:
arr2 = '?'
print(np.corrcoef(arr1, arr2))
Out[1]: 0.3
最佳答案
我已经适应了this answer by whuber从 stats.SE 到 NumPy。这个想法是随机生成第二个数组noise
,然后计算noise
在arr1
上的最小二乘线性回归的残差。残差必然与arr1
相关性为0,当然arr1
与其自身的相关性为1,因此a*arr1 +的适当线性组合b*残差
将具有任何所需的相关性。
import numpy as np
def generate_with_corrcoef(arr1, p):
n = len(arr1)
# generate noise
noise = np.random.uniform(0, 1, n)
# least squares linear regression for noise = m*arr1 + c
m, c = np.linalg.lstsq(np.vstack([arr1, np.ones(n)]).T, noise)[0]
# residuals have 0 correlation with arr1
residuals = noise - (m*arr1 + c)
# the right linear combination a*arr1 + b*residuals
a = p * np.std(residuals)
b = (1 - p**2)**0.5 * np.std(arr1)
arr2 = a*arr1 + b*residuals
# return a scaled/shifted result to have the same mean/sd as arr1
# this doesn't change the correlation coefficient
return np.mean(arr1) + (arr2 - np.mean(arr2)) * np.std(arr1) / np.std(arr2)
最后一行对结果进行缩放,以便平均值和标准差与 arr1
的相同。但是,arr1
和 arr2
的分布并不相同。
用法:
>>> arr1 = np.random.uniform(0, 100, 1000)
>>> arr2 = generate_with_corrcoef(arr1, 0.3)
>>> np.corrcoef(arr1, arr2)
array([[1. , 0.3],
[0.3, 1. ]])
关于python - 生成与现有一维数组具有预先指定相关性的 NumPy 一维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59024703/