Skip to content

ValueError #27

Open
Open

Description

@tongjiezhao

Hi I got this error when running hs = hotspot.Hotspot(
... adata,
... layer_key="csc_counts",
... model='bernoulli',
... latent_obsm_key="spatial",
... umi_counts_obs_key="total_counts",
... )

Traceback (most recent call last):
File "", line 1, in
File "python3.8/site-packages/hotspot/hotspot.py", line 135, in init
raise ValueError(
ValueError:
Detected all zero genes. Please filter adata and reinitialize.

and I try

sc.pp.filter_cells(adata, min_genes=200)
sc.pp.filter_genes(adata, min_cells=3)

it still shows this error
my anndata looks like this
AnnData object with n_obs × n_vars = 1404 × 29522
obs: 'n_genes', 'total_counts'
var: 'highly_variable', 'means', 'dispersions', 'dispersions_norm', 'mean', 'std', 'n_cells'
uns: 'hvg', 'log1p', 'neighbors', 'pca'
obsm: 'X_pca', 'spatial'
varm: 'PCs'
layers: 'csc_counts'
obsp: 'connectivities', 'distances'
and adata.X looks like this
(0, 0) -9.273971
(1, 0) -1.1690428
(2, 0) -2.1527452
(3, 0) 0.29593784
(4, 0) 2.888746
(5, 0) -0.5670085
(6, 0) 0.022515705
(7, 0) -0.3287619
(8, 0) -0.60607976
(9, 0) 3.9856915
(10, 0) 0.59192413
(11, 0) 5.258427
(12, 0) 0.060307246
(13, 0) 0.1517446
(14, 0) 0.29431388
(15, 0) -15.718134
(16, 0) 6.711702
(17, 0) -5.2702594
(18, 0) 0.48261452
(19, 0) 2.9903271
(20, 0) 8.463634
(21, 0) 1.5748714
(22, 0) 1.0938092
(23, 0) 0.44068232
(24, 0) 1.1826563

Activity

  1. Polligator commented on Jul 12, 2022

    @Polligator

    encountered the same error, did you figure out how to resolve it?

  2. coleruoff commented on Jul 28, 2022

    @coleruoff

    I am also encountering this issue...

  3. Polligator commented on Jul 28, 2022

    @Polligator

    One workaround for me was to filter the cell and genes with higher cutoffs, like set min_cell to 20, you just need to tweak on the values.

  4. deto commented on Jul 31, 2022

    @deto
    Member

    Hi everyone, it's hard to guess at what's happening here without your data/code, but if we extract the relevant bits in hotspot.py the check for this essentially does:

    counts = adata.layers[layer_key] if layer_key is not None else adata.X
    counts = counts.transpose()
    valid_genes = counts.sum(axis=1) > 0
    n_invalid = counts.shape[0] - valid_genes.sum()
    if n_invalid > 0:
         raise ValueError(
              "\nDetected all zero genes. Please filter adata and reinitialize."
         )
    

    So as long you had done filtering with sc.pp.filter_genes and min_cell >= 1 it should pass as all remaining genes should have a nonzero sum when summing across cells. Maybe you can run that snippet on your anndata object and it will shed light on why it's not passing the check?

  5. liuxiawei commented on Nov 29, 2024

    @liuxiawei

    I think this problem is caused by the layer name. I found the sc.pp.filter_genes only filter counts layer. when use other layer, The problem happend

  6. CoolCurl commented on Dec 10, 2025

    @CoolCurl
    from scipy import sparse
    # 3) compute per-gene variance on chosen layer
    X = adata.layers['csc_counts']
    if sparse.issparse(X):
        n = X.shape[0]
        # mean and mean of squares without materializing dense matrix
        mean = np.asarray(X.mean(axis=0)).ravel()
        mean_sq = np.asarray(X.multiply(X).mean(axis=0)).ravel()
        var = mean_sq - mean**2
    else:
        var = np.var(X, axis=0)
    
    # 4) quick stats and mask
    print("genes with zero variance:", np.sum(var == 0))
    min_cells = 3   # require gene present in at least this many spots
    if sparse.issparse(X):
        nonzero_counts = np.asarray((X > 0).sum(axis=0)).ravel()
    else:
        nonzero_counts = np.sum(X > 0, axis=0)
    print("genes with <{} nonzero spots:".format(min_cells), np.sum(nonzero_counts < min_cells))
    
    # final mask: non-zero variance and at least min_cells appearances
    mask = (var > 1) & (nonzero_counts >= min_cells)
    print("genes retained:", mask.sum(), " / ", mask.shape[0])
    
    # 5) Subset AnnData to these genes (Hotspot expects anndata with genes filtered)
    adata_f = adata[:, mask].copy()
    print("Filtered adata shape:", adata_f.shape)
    
    # 6) If using bernoulli model, Hotspot expects binary presence/absence. Create a binary layer:
    adata_f.layers['csc_counts_bin'] = (adata_f.layers['csc_counts'] > 0).astype('int8')
    
    # 7) Run Hotspot: use the binary layer name as layer_key for bernoulli
    hs = hotspot.Hotspot(
        adata_f,
        layer_key='csc_counts_bin',   # use binary for 'bernoulli'
        model='bernoulli',
        latent_obsm_key="X_spatial",   # e.g., 'spatial'
        umi_counts_obs_key='total_counts'
    )
    
    hs.create_knn_graph(weighted_graph=False, n_neighbors=300)
    print("Hotspot graph `created.")
    

    i filtered and the layer 'csc_counts_bin' shape like this:

    <Compressed Sparse Column sparse matrix of dtype 'int8'
    with 1075245 stored elements and shape (223, 6362)>
    also has this error.

    genes with zero variance: 247
    genes with <3 nonzero spots: 448
    genes retained: 6362 / 19465
    Filtered adata shape: (223, 6362)

    ValueError Traceback (most recent call last)
    Cell In[53], line 34
    31 adata_f.layers['csc_counts_bin'] = (adata_f.layers['csc_counts'] > 0).astype('int8')
    33 # 7) Run Hotspot: use the binary layer name as layer_key for bernoulli
    ---> 34 hs = hotspot.Hotspot(
    35 adata_f,
    36 layer_key='csc_counts_bin', # use binary for 'bernoulli'
    37 model='bernoulli',
    38 latent_obsm_key="X_spatial", # e.g., 'spatial'
    39 umi_counts_obs_key='total_counts'
    40 )
    42 hs.create_knn_graph(weighted_graph=False, n_neighbors=300)
    43 print("Hotspot graph created.")

    File ~/miniconda3/envs/Celloracle/lib/python3.10/site-packages/hotspot/hotspot.py:148, in Hotspot.init(self, adata, layer_key, model, latent_obsm_key, distances_obsp_key, tree, umi_counts_obs_key)
    146 n_invalid = counts.shape[0] - valid_genes.sum()
    147 if n_invalid > 0:
    --> 148 raise ValueError(
    149 "\nDetected genes with zero variance. Please filter adata and reinitialize."
    150 )
    152 self.adata = adata
    153 self.layer_key = layer_key

    ValueError:
    Detected genes with zero variance. Please filter adata and reinitialize.

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