You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
BUG: ma.corrcoef produces wrong results and takes very long. #15601
In the following code, I calculate the correlation coefficients of an array with missing data in three ways:
Using NumPy’s masked arrays and ma.corrcoef.
Using the corr method of Pandas dataframes.
Going through all pairs and applying np.corrcoef to manually masked arrays.
The results of the last two methods agree which suggests that they are correct. The result using masked arrays does not match, suggesting there is something wrong with it. Moreover, the computation of ma.corrcoef takes excessively long for larger arrays.
importnumpyasnpfrompandasimportDataFrame# Three implementations of the correlation coefficient for missing datacc_masked=lambdadata: np.ma.corrcoef(np.ma.masked_invalid(data))
cc_pandas=lambdadata: DataFrame(data).T.corr().valuesdefcc_manual(data):
n=len(data)
correlation_matrix=np.empty((n,n))
foriinrange(n):
forjinrange(n):
mask=np.isfinite(data[i]) &np.isfinite(data[j])
corr=np.corrcoef( data[i][mask], data[j][mask] )
correlation_matrix[i,j] =corr[0,1]
returncorrelation_matrix# Generate test datan=42m=137q=0.07R=np.random.uniform(-1,1,(n,n))
C=R @ R.Tdata=np.random.multivariate_normal(np.zeros(n),C,m).Tnan_mask=np.random.choice( [True,False], size=data.shape, p=[q,1-q] )
data[nan_mask] =np.nan# Compare correlation coefficientsnp.testing.assert_almost_equal( cc_manual(data), cc_pandas(data) )
np.testing.assert_almost_equal( cc_manual(data), cc_masked(data) )
The bug in ma.corrcoef also occurs in the related ma.cov. They both involve calculating pairwise covariance terms between 1-D arrays a and b of the form np.sum( (a-a.mean())*(b-b.mean()) ) / n. The difference between pandas and ma is use of different means. Both a and b can be masked, and the covariance term involving a and b effectively uses a mask that is the logical or of a and b's masks such that more array elements may be masked in the pairwise covariance term calculation that in the original arrays supplied to the function. ma uses the means of the arrays supplied to the function whereas pandas uses the more correct means of the combined-mask arrays.
Here is a modified version of the OP's example using cov (which is simpler than corrcoef), simpler data, and a function that reproduces both the ma and pandas results depending on the value of the kwarg original_mask.
To me it is not clear which method is better from a mathematical point of view. You could argue that the "wrong" method uses more data to estimate the mean and is therefore better.
I had a look at the R documentation. R implements three main different strategies for handling missing data, in short: producing a NA output, calculating with complete samples only and calculating with all complete pairs in each sample. How I understand it the means are then calculated over complete samples or complete pairs only. These come in variants which control the output ; an example is that instead of NA output it is also possible to raise an error.
The behavior in R is controlled by a keyword argument "use" which can take several values such as: "everything", "complete.obs", "pairwise-complete.obs".
So there are some design questions to solve here. Should the behavior be switchable? Should we ignore the partially incomplete points when calculating a mean?
The long runtimes have been fixed at some point in the last six years, and the results appear to be only slightly different from the reference for real data (with actual correlation structures), so all that remains is the “minor” question of normalisation.
What @ianthomas23 diagnosed in 2020 is still what happens on main. For masked input, ma.cov subtracts from each variable the mean over that variable's own unmasked observations, but the sum of products and the divisor run over the observations the pair shares, which is a different set. ma.corrcoef then divides by variances read off diagonal(cov), which are taken over each variable's own observations again, not over the set the pair shares.
On whether taking the mean over more observations is simply better (@RonaldAJ's question): with row 1 equal to 10 - row 0 the coefficient is exactly -1 on any set of observations, so no choice of convention is at issue.
Here the mean is taken over four observations, the sum of products over the three the pair shares, and corrcoef divides by variances taken over each variable's own four. Taking mean, variance and covariance over the shared observations, the convention of R's use="pairwise.complete.obs" and of pandas.DataFrame.cov/.corr, gives -1. The same mismatch was reported again in gh-20586.
The fix does not bring the per-pair loops back: the one new quantity a pairwise mean needs is the sum of each variable over each pair's shared observations, one matrix product against the indicator matrix that already computes the divisor, so the gh-26285 speedup stays.
Making the convention selectable (use=, also raised by @RonaldAJ) is left open; changing the default to the one other implementations use does not block it.
I have a patch with tests ready and will open a PR in the next few days.
Activity
ianthomas23 commentedon Sep 16, 2020
The bug in
ma.corrcoefalso occurs in the relatedma.cov. They both involve calculating pairwise covariance terms between 1-D arraysaandbof the formnp.sum( (a-a.mean())*(b-b.mean()) ) / n. The difference betweenpandasandmais use of different means. Bothaandbcan be masked, and the covariance term involvingaandbeffectively uses a mask that is the logical or ofaandb's masks such that more array elements may be masked in the pairwise covariance term calculation that in the original arrays supplied to the function.mauses the means of the arrays supplied to the function whereaspandasuses the more correct means of the combined-mask arrays.Here is a modified version of the OP's example using
cov(which is simpler thancorrcoef), simpler data, and a function that reproduces both themaandpandasresults depending on the value of the kwargoriginal_mask.It produces this output
so
original_mask=Falsereproduces thepandasresults andoriginal_mask=Truereproduces themaresults.Use pd.DataFrame.corr instead of np.ma.corrcoef
[-]ma.corrcoef produces wrong results and takes very long.[/-]RonaldAJ commentedon Jun 15, 2023
To me it is not clear which method is better from a mathematical point of view. You could argue that the "wrong" method uses more data to estimate the mean and is therefore better.
I had a look at the R documentation. R implements three main different strategies for handling missing data, in short: producing a NA output, calculating with complete samples only and calculating with all complete pairs in each sample. How I understand it the means are then calculated over complete samples or complete pairs only. These come in variants which control the output ; an example is that instead of NA output it is also possible to raise an error.
The behavior in R is controlled by a keyword argument "use" which can take several values such as: "everything", "complete.obs", "pairwise-complete.obs".
So there are some design questions to solve here. Should the behavior be switchable? Should we ignore the partially incomplete points when calculating a mean?
Wrzlprmft commentedon Mar 1, 2026
The long runtimes have been fixed at some point in the last six years, and the results appear to be only slightly different from the reference for real data (with actual correlation structures), so all that remains is the “minor” question of normalisation.
danggeun commentedon Sep 1, 2026
What @ianthomas23 diagnosed in 2020 is still what happens on main. For masked input,
ma.covsubtracts from each variable the mean over that variable's own unmasked observations, but the sum of products and the divisor run over the observations the pair shares, which is a different set.ma.corrcoefthen divides by variances read offdiagonal(cov), which are taken over each variable's own observations again, not over the set the pair shares.On whether taking the mean over more observations is simply better (@RonaldAJ's question): with row 1 equal to
10 - row 0the coefficient is exactly -1 on any set of observations, so no choice of convention is at issue.Here the mean is taken over four observations, the sum of products over the three the pair shares, and
corrcoefdivides by variances taken over each variable's own four. Taking mean, variance and covariance over the shared observations, the convention of R'suse="pairwise.complete.obs"and ofpandas.DataFrame.cov/.corr, gives -1. The same mismatch was reported again in gh-20586.The fix does not bring the per-pair loops back: the one new quantity a pairwise mean needs is the sum of each variable over each pair's shared observations, one matrix product against the indicator matrix that already computes the divisor, so the gh-26285 speedup stays.
Making the convention selectable (
use=, also raised by @RonaldAJ) is left open; changing the default to the one other implementations use does not block it.I have a patch with tests ready and will open a PR in the next few days.