Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 二维阵列间相关系数的计算_Python_Arrays_Numpy_Scipy_Correlation - Fatal编程技术网

Python 二维阵列间相关系数的计算

Python 二维阵列间相关系数的计算,python,arrays,numpy,scipy,correlation,Python,Arrays,Numpy,Scipy,Correlation,我有两个数组,它们的形状分别为nxt和mxt。我想计算每对可能的行n和m之间的T相关系数(分别来自n和m) 做这件事最快、最像蟒蛇的方法是什么?(在我看来,在N和M上循环既不快也不通畅。)我希望答案包括numpy和/或scipy。现在我的数组是numpyarrays,但我愿意将它们转换为不同的类型 我希望我的输出是一个形状为nxm的数组 注意,当我说“相关系数”时,我指的是 以下是一些需要注意的事项: numpy函数correlate要求输入数组是一维的 numpy函数corrcoef接受二维

我有两个数组,它们的形状分别为
nxt
mxt
。我想计算每对可能的行
n
m
之间的
T
相关系数(分别来自
n
m

做这件事最快、最像蟒蛇的方法是什么?(在我看来,在
N
M
上循环既不快也不通畅。)我希望答案包括
numpy
和/或
scipy
。现在我的数组是
numpy
array
s,但我愿意将它们转换为不同的类型

我希望我的输出是一个形状为
nxm
的数组

注意,当我说“相关系数”时,我指的是

以下是一些需要注意的事项:

  • numpy
    函数
    correlate
    要求输入数组是一维的
  • numpy
    函数
    corrcoef
    接受二维数组,但它们必须具有相同的形状
  • scipy.stats
    函数
    pearsonr
    要求输入数组是一维的
两个2D阵列之间的相关性(默认“有效”情况):

def corr2_coeff(A, B):
    # Rowwise mean of input arrays & subtract from input arrays themeselves
    A_mA = A - A.mean(1)[:, None]
    B_mB = B - B.mean(1)[:, None]

    # Sum of squares across rows
    ssA = (A_mA**2).sum(1)
    ssB = (B_mB**2).sum(1)

    # Finally get corr coeff
    return np.dot(A_mA, B_mB.T) / np.sqrt(np.dot(ssA[:, None],ssB[None]))
你可以像这样简单地使用矩阵乘法-

out = np.dot(arr_one,arr_two.T)
两个输入数组的每个成对行组合(第1行,第2行)之间与默认
“valid”
大小写的相关性将对应于每个(第1行,第2行)位置的乘法结果


两个二维阵列的行相关系数计算:

def corr2_coeff(A, B):
    # Rowwise mean of input arrays & subtract from input arrays themeselves
    A_mA = A - A.mean(1)[:, None]
    B_mB = B - B.mean(1)[:, None]

    # Sum of squares across rows
    ssA = (A_mA**2).sum(1)
    ssB = (B_mB**2).sum(1)

    # Finally get corr coeff
    return np.dot(A_mA, B_mB.T) / np.sqrt(np.dot(ssA[:, None],ssB[None]))
这是基于此解决方案的

基准测试

本节将运行时性能与建议的方法与中列出的基于
generate\u correlation\u map
&loopy
pearsonr
的方法进行比较(取自函数
test\u generate\u correlation\u map()
,末尾没有值正确性验证代码)。请注意,拟议方法的时间安排还包括在开始时检查两个输入数组中的列数是否相等,另一个答案中也是如此。下面列出了运行时

案例1:

案例2:

案例3:

另一种基于pearsonr的循环
方法似乎太慢,但下面是一个小数据量的运行时-

In [118]: A = np.random.rand(1000, 100)

In [119]: B = np.random.rand(1000, 100)

In [120]: %timeit corr2_coeff(A, B)
100 loops, best of 3: 15.3 ms per loop

In [121]: %timeit generate_correlation_map(A, B)
100 loops, best of 3: 19.7 ms per loop

In [122]: %timeit pearsonr_based(A, B)
1 loops, best of 3: 33 s per loop
两个二维数组之间的相关性(默认“有效”情况):

def corr2_coeff(A, B):
    # Rowwise mean of input arrays & subtract from input arrays themeselves
    A_mA = A - A.mean(1)[:, None]
    B_mB = B - B.mean(1)[:, None]

    # Sum of squares across rows
    ssA = (A_mA**2).sum(1)
    ssB = (B_mB**2).sum(1)

    # Finally get corr coeff
    return np.dot(A_mA, B_mB.T) / np.sqrt(np.dot(ssA[:, None],ssB[None]))
你可以像这样简单地使用矩阵乘法-

out = np.dot(arr_one,arr_two.T)
两个输入数组的每个成对行组合(第1行,第2行)之间与默认
“valid”
大小写的相关性将对应于每个(第1行,第2行)位置的乘法结果


两个二维阵列的行相关系数计算:

def corr2_coeff(A, B):
    # Rowwise mean of input arrays & subtract from input arrays themeselves
    A_mA = A - A.mean(1)[:, None]
    B_mB = B - B.mean(1)[:, None]

    # Sum of squares across rows
    ssA = (A_mA**2).sum(1)
    ssB = (B_mB**2).sum(1)

    # Finally get corr coeff
    return np.dot(A_mA, B_mB.T) / np.sqrt(np.dot(ssA[:, None],ssB[None]))
这是基于此解决方案的

基准测试

本节将运行时性能与建议的方法与中列出的基于
generate\u correlation\u map
&loopy
pearsonr
的方法进行比较(取自函数
test\u generate\u correlation\u map()
,末尾没有值正确性验证代码)。请注意,拟议方法的时间安排还包括在开始时检查两个输入数组中的列数是否相等,另一个答案中也是如此。下面列出了运行时

案例1:

案例2:

案例3:

另一种基于pearsonr的循环
方法似乎太慢,但下面是一个小数据量的运行时-

In [118]: A = np.random.rand(1000, 100)

In [119]: B = np.random.rand(1000, 100)

In [120]: %timeit corr2_coeff(A, B)
100 loops, best of 3: 15.3 ms per loop

In [121]: %timeit generate_correlation_map(A, B)
100 loops, best of 3: 19.7 ms per loop

In [122]: %timeit pearsonr_based(A, B)
1 loops, best of 3: 33 s per loop

@Divakar为计算无标度相关性提供了一个很好的选择,这正是我最初要求的

为了计算相关系数,需要更多:

import numpy as np

def generate_correlation_map(x, y):
    """Correlate each n with each m.

    Parameters
    ----------
    x : np.array
      Shape N X T.

    y : np.array
      Shape M X T.

    Returns
    -------
    np.array
      N X M array in which each element is a correlation coefficient.

    """
    mu_x = x.mean(1)
    mu_y = y.mean(1)
    n = x.shape[1]
    if n != y.shape[1]:
        raise ValueError('x and y must ' +
                         'have the same number of timepoints.')
    s_x = x.std(1, ddof=n - 1)
    s_y = y.std(1, ddof=n - 1)
    cov = np.dot(x,
                 y.T) - n * np.dot(mu_x[:, np.newaxis],
                                  mu_y[np.newaxis, :])
    return cov / np.dot(s_x[:, np.newaxis], s_y[np.newaxis, :])
下面是此函数的测试,它通过了:

from scipy.stats import pearsonr

def test_generate_correlation_map():
    x = np.random.rand(10, 10)
    y = np.random.rand(20, 10)
    desired = np.empty((10, 20))
    for n in range(x.shape[0]):
        for m in range(y.shape[0]):
            desired[n, m] = pearsonr(x[n, :], y[m, :])[0]
    actual = generate_correlation_map(x, y)
    np.testing.assert_array_almost_equal(actual, desired)

@Divakar为计算无标度相关性提供了一个很好的选择,这正是我最初要求的

为了计算相关系数,需要更多:

import numpy as np

def generate_correlation_map(x, y):
    """Correlate each n with each m.

    Parameters
    ----------
    x : np.array
      Shape N X T.

    y : np.array
      Shape M X T.

    Returns
    -------
    np.array
      N X M array in which each element is a correlation coefficient.

    """
    mu_x = x.mean(1)
    mu_y = y.mean(1)
    n = x.shape[1]
    if n != y.shape[1]:
        raise ValueError('x and y must ' +
                         'have the same number of timepoints.')
    s_x = x.std(1, ddof=n - 1)
    s_y = y.std(1, ddof=n - 1)
    cov = np.dot(x,
                 y.T) - n * np.dot(mu_x[:, np.newaxis],
                                  mu_y[np.newaxis, :])
    return cov / np.dot(s_x[:, np.newaxis], s_y[np.newaxis, :])
下面是此函数的测试,它通过了:

from scipy.stats import pearsonr

def test_generate_correlation_map():
    x = np.random.rand(10, 10)
    y = np.random.rand(20, 10)
    desired = np.empty((10, 20))
    for n in range(x.shape[0]):
        for m in range(y.shape[0]):
            desired[n, m] = pearsonr(x[n, :], y[m, :])[0]
    actual = generate_correlation_map(x, y)
    np.testing.assert_array_almost_equal(actual, desired)

对于那些对计算一维和二维数组之间的皮尔逊相关系数感兴趣的人,我编写了以下函数,
x
是一维数组,
y
是二维数组

def pearsonr_2D(x, y):
    """computes pearson correlation coefficient
       where x is a 1D and y a 2D array"""

    upper = np.sum((x - np.mean(x)) * (y - np.mean(y, axis=1)[:,None]), axis=1)
    lower = np.sqrt(np.sum(np.power(x - np.mean(x), 2)) * np.sum(np.power(y - np.mean(y, axis=1)[:,None], 2), axis=1))
    
    rho = upper / lower
    
    return rho
运行示例:

>>> x
Out[1]: array([1, 2, 3])

>>> y
Out[2]: array([[ 1,  2,  3],
               [ 6,  7, 12],
               [ 9,  3,  1]])

>>> pearsonr_2D(x, y)
Out[3]: array([ 1.        ,  0.93325653, -0.96076892])

对于那些对计算一维和二维数组之间的皮尔逊相关系数感兴趣的人,我编写了以下函数,
x
是一维数组,
y
是二维数组

def pearsonr_2D(x, y):
    """computes pearson correlation coefficient
       where x is a 1D and y a 2D array"""

    upper = np.sum((x - np.mean(x)) * (y - np.mean(y, axis=1)[:,None]), axis=1)
    lower = np.sqrt(np.sum(np.power(x - np.mean(x), 2)) * np.sum(np.power(y - np.mean(y, axis=1)[:,None], 2), axis=1))
    
    rho = upper / lower
    
    return rho
运行示例:

>>> x
Out[1]: array([1, 2, 3])

>>> y
Out[2]: array([[ 1,  2,  3],
               [ 6,  7, 12],
               [ 9,  3,  1]])

>>> pearsonr_2D(x, y)
Out[3]: array([ 1.        ,  0.93325653, -0.96076892])

那么,您是在寻找
“相同的”
“完整的”
,还是使用
np.correlate
?您是否编写了解决方案的循环版本?我在寻找
“有效的”
。是的,循环版本很简单:
对于范围内的n(n):
对于范围内的m:
相关(arr\n,:],arr_two[m,:])
…那么您是在寻找
“相同的”
“完整的”
,还是带有
np.correlate
的默认值?您编写了解决方案的循环版本吗?我正在寻找
'valid'
。是的,循环版本很简单:
用于范围(n)中的n:
<代码>适用于范围内的m(m):
<代码>关联(arr_one[n,:],arr_two[m,:])
。美好的我没有意识到
newaxis
None
的别名。我认为您缺少了一个
,:
,从第二行到最后一行的
sb1
。与double for loop方法相比,对我们的答案计时是很有趣的。@dbliss认为[None]是有意的,将其作为行向量,而另一个是列向量,带有[:,None]。使广播发挥作用所需要的一切。添加了运行时测试,请查看这些测试。做得不错,但我不确定您报告的计时结果信息量有多大。例如,