python - 生成与现有一维数组具有预先指定相关性的 NumPy 一维数组?

标签 python arrays numpy

我有一个未生成的一维 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,然后计算noisearr1上的最小二乘线性回归的残差。残差必然与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 的相同。但是,arr1arr2 的分布并不相同。

用法:

>>> 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/

相关文章:

php - 运行非常长的脚本 - 如何让它们保持运行并在它们失败时重新启动它们?

python - 如何查询并从函数中获取最大值

javascript - 将消息数组拆分为对话

python - 从 numpy 数组创建值频率字典

python - 如何替换 NumPy 数组中的单行

python - numpy 的平均值大于 memmap 的最大值

python - 将列表拆分为两个具有相似元素的子列表

python - Django 中的 MaxMind GeoIP2 单实例

python - 如何从列表中的项目中删除标点符号并将其另存为列表中的单独项目?

c - 在C中向数组添加值不起作用