python - numpy.ma.cov - 与缺失值的成对相关性?

标签 python numpy

示例数据集(行是从一个更大的矩阵中随机提取的)

import numpy as np

test = [[np.nan, np.nan, 0.217, 0.562],
        [np.nan, np.nan, 0.217, 0.562],
        [0.269, 0.0, 0.217, 0.562],
        [np.nan, np.nan, 0.217, -0.953],
        [np.nan, np.nan, 0.217, -0.788],
        [0.75, 0.0, 0.217, 0.326],
        [0.207, 0.0, 0.217, 0.814],
        [np.nan, np.nan, 0.217, 0.562],
        [np.nan, np.nan, 0.217, -0.022],
        [np.nan, np.nan, 0.217, 0.562],
        [np.nan, np.nan, 0.217, -0.953],
        [np.nan, np.nan, 0.217, -0.953],
        [0.078, 0.0, 0.217, -0.953],
        [np.nan, np.nan, 0.217, -0.953],
        [0.078, 0.0, 0.217, 0.562]]

maskedarr = np.ma.array(test)

np.ma.cov(maskedarr,rowvar=False,allow_masked=True)

[[-- -- -- --]
 [-- -- -- --]
 [-- -- 0.0 0.0]
 [-- -- 0.0 0.554]]

但是,如果我使用 R,

import rpy2.robjects as robjects

robjects.globalenv['maskedarr'] = robjects.FloatVector(maskedarr.T.flatten())
robjects.r('''
dim(maskedarr) <- c(%d,%d)
maskedarr[] <- replace(maskedarr,!is.finite(maskedarr),NA)
''' % maskedarr.shape)
robjects.r('''
print(cov(maskedarr,use="pairwise"))
''')

          [,1] [,2] [,3]      [,4]
[1,] 0.0769733    0    0 0.0428294
[2,] 0.0000000    0    0 0.0000000
[3,] 0.0000000    0    0 0.0000000
[4,] 0.0428294    0    0 0.5536484

我得到一个非常不同的矩阵。如果仅针对该对删除了 nan 的成对相关性,那么我会期待类似 R 的答案 - numpy.ma.covallow_masked= True 将允许计算这些成对相关性,但似乎并非如此。我错过了什么吗?

最佳答案

您的 maskedarr 没有任何值被屏蔽。

>>> maskedarr.mask
False

初始化数组时需要包含mask参数。

>>> maskedarr = np.ma.array(test, mask=np.isnan(test))

现在maskedarr.mask如下。

>>> maskedarr.mask
array([[ True,  True, False, False],
       [ True,  True, False, False],
       [False, False, False, False],
       [ True,  True, False, False],
       [ True,  True, False, False],
       [False, False, False, False],
       [False, False, False, False],
       [ True,  True, False, False],
       [ True,  True, False, False],
       [ True,  True, False, False],
       [ True,  True, False, False],
       [ True,  True, False, False],
       [False, False, False, False],
       [ True,  True, False, False],
       [False, False, False, False]], dtype=bool)

这次在执行 numpy.ma.cov 时:

>>> np.ma.cov(maskedarr,rowvar=False,allow_masked=True)
masked_array(data =
 [[0.0769732996251 0.0 0.0 0.0428294015418]
 [0.0 0.0 0.0 0.0]
 [0.0 0.0 0.0 0.0]
 [0.0428294015418 0.0 0.0 0.553648402899]],
             mask =
 [[False False False False]
 [False False False False]
 [False False False False]
 [False False False False]],
       fill_value = 1e+20)

关于python - numpy.ma.cov - 与缺失值的成对相关性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8287573/

相关文章:

python - 将 np.tril 和 np.triu 堆叠在一起

python - 通过 numpy 切片/跨步进行 OpenCV BGR2RGB 转换

python - 如何使用 PyPlot 绘制带有 2 个 slider 的 4D 数组?

Python。结果不正确

python - 无法从 String 生成输出差异

python - 如何创建列表列表

python - 向量化这个 for 循环

python - 解析 .txt 文件

python - 当使用 metrics= ['accuracy' ] 时,Keras 使用了什么精度函数?

python - 移动数据帧的列而不循环?