Skip to content

t-tests fails when variance of both groups is 0 #620

Closed

Description

@ivirshup

So I was writing a test for rank_genes_groups_df from #619 when I got some results that seem pretty wrong. Here's an example:

import scanpy as sc

import numpy as np
import pandas as pd
from scipy import stats

from itertools import repeat, chain

# Making data where "gene0" is definitely differentially expressed.

a = np.zeros((20, 3))
a[:10, 0] = 5
adata = sc.AnnData(
    a,
    obs=pd.DataFrame(
        {"celltype": list(chain(repeat("a", 10), repeat("b", 10)))},
        index=[f"cell{i}" for i in range(a.shape[0])]
    ),
    var=pd.DataFrame(index=[f"gene{i}" for i in range(a.shape[1])]),
)

# Running differential expression with t-test:

sc.tl.rank_genes_groups(adata, groupby="celltype")
print(adata.uns["rank_genes_groups"]["pvals"]["a"])
# array([1., 1., 1.])  # This seems wrong

sc.tl.rank_genes_groups(adata, groupby="celltype", method="t-test")
print(adata.uns["rank_genes_groups"]["pvals"]["a"])
# array([1., 1., 1.])  # This also seems wrong

# Checking to make sure I'm not forgetting something obvious
print(stats.ttest_ind([0,0,0,0,0], [5,5,5,5,5]))
# Ttest_indResult(statistic=-inf, pvalue=0.0)   # This seems right

# Wilcoxon seems fine:

sc.tl.rank_genes_groups(adata, groupby="celltype", method="wilcoxon")
print(adata.uns["rank_genes_groups"]["pvals"]["a"])
# array([1.57052284e-04, 1.00000000e+00, 1.00000000e+00])  # This seems right

"logreg" on the other hand, throws an error:

sc.tl.rank_genes_groups(adata, groupby="celltype", method="logreg")
<ipython-input-7-29e46f287a31> in <module>
----> 1 sc.tl.rank_genes_groups(adata, groupby="celltype", method="logreg")

~/github/scanpy/scanpy/tools/_rank_genes_groups.py in rank_genes_groups(adata, groupby, use_raw, groups, reference, n_genes, rankby_abs, key_added, copy, method, corr_method, log_transformed, **kwds)
    397     adata.uns[key_added]['scores'] = np.rec.fromarrays(
    398         [n for n in rankings_gene_scores],
--> 399         dtype=[(rn, 'float32') for rn in groups_order_save])
    400     adata.uns[key_added]['names'] = np.rec.fromarrays(
    401         [n for n in rankings_gene_names],

/usr/local/lib/python3.7/site-packages/numpy/core/records.py in fromarrays(arrayList, dtype, shape, formats, names, titles, aligned, byteorder)
    615     # Determine shape from data-type.
    616     if len(descr) != len(arrayList):
--> 617         raise ValueError("mismatch between the number of fields "
    618                 "and the number of arrays")
    619 

Activity

  1. LuckyMD commented on Apr 25, 2019

    @LuckyMD
    Contributor

    This seems to have something to do with not being able to estimate the variance within a group. If you add thes lines:

    adata.X[0,:] = np.array([1.,1.,1.])
    adata.X[11,:] = np.array([1.,1.,1.])
    

    to your data, then it works as expected.

    I assume this is due to NaN being set to 1 in the p-value calculation. The t-test isn't defined in this case. Not sure what the error for "logreg" is though.

  2. LuckyMD commented on Apr 25, 2019

    @LuckyMD
    Contributor

    Btw. I think scanpy uses Welch's t-test and not the standard t-test. So the comparison with stats.ttest_ind is not entirely correct. I guess stats.ttest_ind calculates the asymptote of the statistic (-inf) and uses that to give a p-value of 0.0.

  3. ivirshup commented on Apr 25, 2019

    @ivirshup
    MemberAuthor

    I don't think it should matter whether it's Welch's in this case, since the population variances are both zero, right? Anyways, scipy's Welch's gives the same result:

    print(stats.ttest_ind([0,0,0,0,0], [5,5,5,5,5], equal_var=False))                          
    Ttest_indResult(statistic=-inf, pvalue=0.0)

    I currently suspect this bit of code for the bug:

    https://github.com/theislab/scanpy/blob/00471636b050bf42ef41cc9ba0d45783de6b32e6/scanpy/tools/_rank_genes_groups.py#L198-L201

  4. LuckyMD commented on Apr 25, 2019

    @LuckyMD
    Contributor

    It doesn't matter for the topic of this discussion indeed. I reckon line 201 is the cause.

    If you want to solve this as scipy does, you will probably have to test for 0 variance and then assign a -Inf score, which defaults to a p-value of 0. I wonder if you get spurious marker gene results then though.

  5. ivirshup commented on Apr 25, 2019

    @ivirshup
    MemberAuthor

    Turns out np.divide does the reasonable thing. But also this appears to only be the start of the problem.

  6. ivirshup commented on Apr 25, 2019

    @ivirshup
    MemberAuthor

    A lot of denominators being set to 0 when they should be inf here ಠ_ಠ

  7. changed the title [-]Differentially expressed gene not being picked up?[/-] [+]t-tests fails when variance of both groups is 0[/+] on Apr 26, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions