示例数据集(行从更大的矩阵中随机提取)
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.cov
表示allow_masked=True
将允许计算这些成对相关性,但是似乎并非如此。我错过了什么吗?
答案 0 :(得分:6)
您的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)