Skip to content

bugfix for #1725 - #1732

Merged
ivirshup merged 6 commits into
scverse:masterfrom
jlause:hvg_meanvar_bug
Mar 19, 2021
Merged

ivirshup merged 6 commits into
scverse:masterfrom
jlause:hvg_meanvar_bug

Conversation

@jlause

@jlause jlause commented Mar 10, 2021 •

Copy link
Copy Markdown
Contributor

Fixed by computing global mean/variance outside the batch for loop :)

Verification code (same as in #1725):

import numpy as np
import scanpy as sc
import anndata 

import sys
sys.path.append("scanpy/preprocessing")
from _utils import _get_mean_var

np.random.seed(42)
adata = anndata.AnnData(np.random.randint(0,5,(100,100)))
adata.obs['batch'] = np.random.randint(0,5,(100))

#show that without batch_key, everything works fine
true_mean,true_var = _get_mean_var(adata.X)
result = sc.pp.highly_variable_genes(adata,n_top_genes=2,flavor='seurat_v3',inplace=False)
print('Results correct without batch_key?')
print(np.all(result['means']==true_mean))
print(np.all(result['variances']==true_var))

#show that it goes wrong with batch_key..
result_with_batchkey = sc.pp.highly_variable_genes(adata,n_top_genes=2,flavor='seurat_v3',inplace=False,batch_key='batch')
print('Results correct with batch_key?')
print(np.all(result_with_batchkey['means']==true_mean))
print(np.all(result_with_batchkey['variances']==true_var))

#..and that the wrong result comes from the last batch
adata_batch4 = adata[adata.obs['batch']==4,:].copy()
means_batch4,vars_batch4 = _get_mean_var(adata_batch4.X)
print('Wrong results come from last batch?')
print(np.all(result_with_batchkey['means']==means_batch4))
print(np.all(result_with_batchkey['variances']==vars_batch4))

Verification code output:

Results correct without batch_key?
True
True
Results correct with batch_key?
True
True
Wrong results come from last batch?
False
False

/gpfs01/berens/user/jlause/libs/scanpy/scanpy/preprocessing/_highly_variable_genes.py:148: FutureWarning: Slicing a positional slice with .loc is not supported, and will raise TypeError in a future version.  Use .loc with labels or .iloc with positions instead.
  df.loc[: int(n_top_genes), 'highly_variable'] = True
/gpfs01/berens/user/jlause/libs/scanpy/scanpy/preprocessing/_highly_variable_genes.py:148: FutureWarning: Slicing a positional slice with .loc is not supported, and will raise TypeError in a future version.  Use .loc with labels or .iloc with positions instead.
  df.loc[: int(n_top_genes), 'highly_variable'] = True

@codecov

codecov Bot commented Mar 10, 2021 •

Copy link
Copy Markdown

Codecov Report

Merging #1732 (2827883) into master (1eafe3d) will decrease coverage by 0.00%.
The diff coverage is 100.00%.

@@            Coverage Diff             @@
##           master    #1732      +/-   ##
==========================================
- Coverage   71.31%   71.31%   -0.01%     
==========================================
  Files          91       91              
  Lines       11114    11113       -1     
==========================================
- Hits         7926     7925       -1     
  Misses       3188     3188              
Impacted Files Coverage Δ
scanpy/preprocessing/_highly_variable_genes.py 94.76% <100.00%> (-0.11%) ⬇️
scanpy/tools/_rank_genes_groups.py 94.10% <0.00%> (+0.05%) ⬆️

@ivirshup ivirshup left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fix!

Could this get a test, and a note in the 1.7.2 changelog?

"`flavor='seurat_v3'` expects raw count data, but non-integers were found.",
UserWarning,
)
mean_fulldataset, var_fulldataset = _get_mean_var(X)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could remove the variables if they're not used anywhere else:

df["mean"], df["var"] =  _get_mean_var(X)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good point, thanks!

@ivirshup ivirshup added this to the 1.7.2 milestone Mar 11, 2021
@jlause

jlause commented Mar 11, 2021

Copy link
Copy Markdown
Contributor Author

I updated release notes and added a test for this specific case. I did not write many tests before, so I looked at the other tests and tried to stick to what I saw there.

I noted something unexpected when writing the test: When used np.mean and np.var(.., ddof=1) to compare against the test failed because some of the variances were off. The current version of the test uses sc.pp._utils._get_mean_var() (thats what highly_variable_genes() uses internally...), and does not fail..

Is it ok to use that instead? Is it expected that numpy and _get_mean_var() are slightly different here?

Test code with numpy ground truth:

def test_seurat_v3_mean_var_output_with_batchkey_vs_numpy():
    pbmc = sc.datasets.pbmc3k()
    pbmc.var_names_make_unique()
    n_cells = pbmc.shape[0]
    batch = np.zeros((n_cells), dtype=int)
    batch[1500:] = 1
    pbmc.obs["batch"] = batch

    true_mean = np.mean(pbmc.X.toarray(), axis=0)
    true_var = np.var(pbmc.X.toarray(), axis=0, ddof=1)

    result_df = sc.pp.highly_variable_genes(
        pbmc, batch_key='batch', flavor='seurat_v3', n_top_genes=4000, inplace=False
    )
    np.testing.assert_allclose(true_mean, result_df['means'], rtol=2e-05, atol=2e-05)
    np.testing.assert_allclose(true_var, result_df['variances'], rtol=2e-05, atol=2e-05)

Test output:

E       AssertionError: 
E       Not equal to tolerance rtol=2e-05, atol=2e-05
E       
E       Mismatched elements: 172 / 32738 (0.525%)
E       Max absolute difference: 0.01117667
E       Max relative difference: 0.00013328
E        x: array([0., 0., 0., ..., 0., 0., 0.], dtype=float32)
E        y: array([0., 0., 0., ..., 0., 0., 0.])

tests/test_highly_variable_genes.py:279: AssertionError

@giovp

giovp commented Mar 12, 2021

Copy link
Copy Markdown
Member

Is it ok to use that instead? Is it expected that numpy and _get_mean_var() are slightly different here?

very interesting, just checked sc.pp._utils._get_mean_var() and noticed that variance is not calcualted with np.var. Would that makes sense to change in _utils to use np.var ?

https://github.com/theislab/scanpy/blob/af8f323ebca87bc98d51e556742acf3c2cdf56e9/scanpy/preprocessing/_utils.py#L6

@jlause

jlause commented Mar 12, 2021 •

Copy link
Copy Markdown
Contributor Author

Is it ok to use that instead? Is it expected that numpy and _get_mean_var() are slightly different here?

very interesting, just checked sc.pp._utils._get_mean_var() and noticed that variance is not calcualted with np.var. Would that makes sense to change in _utils to use np.var ?

https://github.com/theislab/scanpy/blob/af8f323ebca87bc98d51e556742acf3c2cdf56e9/scanpy/preprocessing/_utils.py#L6

I'm not experienced enough to say if what currently happens is maybe more efficient than np.var()?!

I think the deviating values I reported above come from what happens in the sparse case (sparse_mean_variance_axis()).. I can check next week if the same deviations occurs for the nonsparse case.

PS: As I said before, not even sure if these deviations are maybe even expected because of the different way of computing the variance here?!

@ivirshup

Copy link
Copy Markdown
Member

Calculating the variance on 32 bit floats, especially in the value ranges you have for counts, will result in a fair bit of inaccuracy. Because of this, we calculate variance with 64 bit values internally. To demonstrate:

import scanpy as sc, numpy as np
from scanpy.pp._utils import _get_mean_var

pbmc = sc.datasets.pbmc3k()

var_np32 = np.var(pbmc.X.toarray(), axis=0, ddof=1)
var_np64 = np.var(pbmc.X.toarray(), axis=0, ddof=1, dtype=np.float64)
_, var_scanpy = _get_mean_var(pbmc.X)

# These are close
np.testing.assert_allclose(var_np64, var_scanpy)

# Same values are different
assert (np.isclose(var_np32, var_np64) == np.isclose(var_np32, var_scanpy)).all()

We don't use the numpy function for variance because then we'd need to create a dense intermediate array. We've previously used sklearn.utils.sparsefuncs.mean_variance_axis but that didn't let us control ddof or collect to 64 bit values from 32 bit input.

@jlause

jlause commented Mar 18, 2021

Copy link
Copy Markdown
Contributor Author

Thanks for the demo code! now its clear to me.

I adapted the test to use np.var(..,dtype=np.float64) as ground truth, making the internal datatype conversion explicit.

Any other requests? I think everything else is ready :)

@ivirshup ivirshup left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, thanks!

I'm just going to make a little clean up of the existing code, but this should be good to go.

@ivirshup
ivirshup enabled auto-merge (squash) March 19, 2021 06:13
@ivirshup
ivirshup merged commit 05792b1 into scverse:master Mar 19, 2021
ivirshup added a commit to ivirshup/scanpy that referenced this pull request Mar 19, 2021
* fixes scverse#1725

* removed unneeded mean_fulldataset/var_fulldataset variables

* release note and tests

* making variance dtype explicit in test

* Minor cleanup -- ivirshup

Co-authored-by: Isaac Virshup <[email protected]>
@scverse scverse deleted a comment from lumberbot-app Bot Oct 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants