协方差矩阵 Python - 省略 -9999 值

Covariance Matrix Python - Omit -9999 Value

我正在尝试使用 python 计算两个完全重叠图像的协方差矩阵。相同的代码是:

stacked = np.vstack((image1.ravel(),image2.ravel()))
np.cov(stacked)

是否有克服NoData问题并正确计算协方差矩阵的价值?

您最好的选择是使用 numpy 的屏蔽数组提供的方法,其中之一是在存在屏蔽项时计算协方差矩阵:

>>> import numpy as np
>>> mask_value = -9999
>>> a = np.array([1, 2, mask_value, 4])
>>> b = np.array([1, mask_value, 3, 4])
>>> c = np.vstack((a,b))
>>> 
>>> masked_a, masked_b, masked_c = [np.ma.array(x, mask=x==mask_value) for x in (a,b,c)]  # note: testing for equality is a bad idea if you're working with floats. I'm not, these are integers, so it's okay.
>>> 
>>> result = np.ma.cov(masked_c)
>>> result
masked_array(data =
 [[2.333333333333333 4.444444444444445]
 [4.444444444444445 2.333333333333333]],
             mask =
 [[False False]
 [False False]],
       fill_value = 1e+20)

>>> np.cov([1,2,4]) # autocovariance when just one element is masked is the same as the previous result[0,0]
array(2.333333333333333)

结果因调用方式不同而不同np.ma.cov:

>>> np.ma.cov(masked_a, masked_b)
masked_array(data =
 [[4.5 4.5]
 [4.5 4.5]],
             mask =
 [[False False]
 [False False]],
       fill_value = 1e+20)

>>> np.cov([1,4])  # result of the autocovariance when 2 of the 4 values are masked
array(4.5)

原因是后一种方法结合了 2 个变量的掩码,如下所示:

>>> mask2 = masked_c.mask.any(axis=0)
>>> all_masked_c = np.ma.array(c, mask=np.vstack((mask2, mask2)))
>>> all_masked_c
masked_array(data =
 [[1 -- -- 4]
 [1 -- -- 4]],
             mask =
 [[False  True  True False]
 [False  True  True False]],
       fill_value = 999999)

>>> np.ma.cov(all_masked_c) # same function call as the first approach, but with a different mask!
masked_array(data =
 [[4.5 4.5]
 [4.5 4.5]],
             mask =
 [[False False]
 [False False]],
       fill_value = 1e+20)

因此请使用 np.ma.cov,但请注意当存在非重叠屏蔽值时您希望如何解释数据。