Skip to content

Reference handling with .obsm causing trouble with umap.transform (maybe?) #138

Closed

Description

@ivirshup

Edit: I've now managed to completely factor AnnData out of this bug. It turns out it's an issue with passing views of recarrays to UMAP. See this #138 (comment) for a minimal example without AnnData.


Alright, this is a bit of a weird one. I'm trying to project simulated doublets into a UMAP of the real data. The initial embedding is being modified when I try to transform the simulated doublets. This only seems to occur if there are the same amount of simulated doublets as initial cells. I spent the last day thinking was a problem with UMAP, until I couldn't replicate without using Scanpy and AnnData, so my current theory is it has to do with getters and setters for .obsm. I could also be doing something dumb and just not seeing it.

I've put everything needed to reproduce in this gist (sorry about the length, I'm having trouble cutting it down). Basically, this code gives weird looking results and throws an error:

umap = UMAP()
pbmc.obsm["X_umap"] = umap.fit_transform(pbmc.obsm["X_pca"])
assert np.allclose(pbmc.obsm["X_umap"], umap.embedding_)
dblt.obsm["X_umap"] = umap.transform(dblt.obsm["X_pca"])
assert np.allclose(pbmc.obsm["X_umap"], umap.embedding_)  # This assertion fails

This code does not:

umap = UMAP()
pbmc_umap = umap.fit_transform(pbmc.obsm["X_pca"])
assert np.allclose(pbmc_umap, umap.embedding_)
dblt_umap = umap.transform(dblt.obsm["X_pca"])
assert np.allclose(pbmc_umap, umap.embedding_)

Activity

  1. ivirshup commented on Apr 14, 2019

    @ivirshup
    MemberAuthor

    Managed to cut down the example by a lot:

    import numpy as np
    from scipy import sparse
    from umap import UMAP
    import scanpy as sc
    
    def pca_update(tgt, src, inplace=True):
        # TODO: Make sure we know the settings from src
        if not inplace:
            tgt = tgt.copy()
        if sparse.issparse(tgt.X):
            X = tgt.X.toarray()
        else:
            X = tgt.X.copy()
        X -= np.asarray(tgt.X.mean(axis=0))
        tgt_pca = np.dot(X, src.varm["PCs"])
        tgt.obsm["X_pca"] = tgt_pca
        return tgt
    
    pbmc = sc.datasets.pbmc68k_reduced()
    sc.pp.pca(pbmc)
    pbmc2 = pbmc.copy()
    pca_update(pbmc2, pbmc)
    
    umap = UMAP()
    pbmc.obsm["X_umap"] = umap.fit_transform(pbmc.obsm["X_pca"])
    assert np.allclose(pbmc.obsm["X_umap"], umap.embedding_)
    pbmc2.obsm["X_umap"] = umap.transform(pbmc2.obsm["X_pca"])
    assert np.allclose(pbmc.obsm["X_umap"], umap.embedding_)

    Looks like it has something to do with the pca update function, if I just pass the copy to umap.transform there is no error.

    Edit: 😕

    pbmc = sc.datasets.pbmc68k_reduced()
    pbmc2 = pbmc.copy()
    pbmc2.obsm["X_pca"] = np.dot(
        pbmc.obsm["X_pca"], 
        np.eye(pbmc.obsm["X_pca"].shape[1])
    )
    np.all(pbmc2.obsm["X_pca"] == pbmc.obsm["X_pca"])
    
    umap = UMAP()
    pbmc.obsm["X_umap"] = umap.fit_transform(pbmc.obsm["X_pca"])
    assert np.allclose(pbmc.obsm["X_umap"], umap.embedding_)
    pbmc2.obsm["X_umap"] = umap.transform(pbmc2.obsm["X_pca"])
    assert np.allclose(pbmc.obsm["X_umap"], umap.embedding_)  # Still throws error

    Edit 2: Closer

    If I pass a copy of the original cell loadings to the fit_transform there is no error.

    pbmc = sc.datasets.pbmc68k_reduced()
    pbmc2 = pbmc.copy()
    pbmc2.obsm["X_pca"] = np.dot(
        pbmc.obsm["X_pca"], 
        np.eye(pbmc.obsm["X_pca"].shape[1])
    )
    
    umap = UMAP()
    pbmc.obsm["X_umap"] = umap.fit_transform(pbmc.obsm["X_pca"].copy())
    assert np.allclose(pbmc.obsm["X_umap"], umap.embedding_)
    pbmc2.obsm["X_umap"] = umap.transform(pbmc2.obsm["X_pca"])
    assert np.allclose(pbmc.obsm["X_umap"], umap.embedding_)  # This does not error
  2. falexwolf commented on Apr 15, 2019

    @falexwolf
    Member

    Doesn't your last example suggest that the umap instance does some changes to pbmc.obsm["X_pca"] (which gives a view on .obsm by virtue of how numpy structured arrays work) via fit_transform if you can resolve it via .copy()?

  3. ivirshup commented on Apr 15, 2019

    @ivirshup
    MemberAuthor

    It doesn't look like it changes the values:

    import scanpy as sc
    import numpy as np
    from umap import UMAP
    import joblib  # UMAP internally hashes data this way
    
    a = sc.datasets.pbmc68k_reduced()
    b = a.copy()
    b.obsm["X_pca"] = np.dot(
        a.obsm["X_pca"], 
        np.eye(a.obsm["X_pca"].shape[1])
    )
    
    apca = a.obsm["X_pca"]
    bpca = b.obsm["X_pca"]
    
    print(joblib.hash(apca), "apca")
    print(joblib.hash(bpca), "bpca")
    
    umap = UMAP()
    u = umap.fit_transform(apca)
    u_orig = u.copy()
    print(joblib.hash(umap._raw_data))
    print(joblib.hash(apca))
    assert np.allclose(u, u_orig)
    umap.transform(bpca)
    print(joblib.hash(apca))
    print(joblib.hash(umap._raw_data))
    assert np.allclose(u, u_orig)
    # 68d1208f4a3c65dbf2217e511d6aa8e6 apca
    # cc58c1030b1b4880344131106b00c5f0 bpca
    # 68d1208f4a3c65dbf2217e511d6aa8e6
    # 68d1208f4a3c65dbf2217e511d6aa8e6
    # 68d1208f4a3c65dbf2217e511d6aa8e6
    # 68d1208f4a3c65dbf2217e511d6aa8e6
    # ---------------------------------------------------------------------------
    # AssertionError                            Traceback (most recent call last)
    # <ipython-input-105-6881f6a8ec92> in <module>
    #      26 print(joblib.hash(apca))
    #      27 print(joblib.hash(umap._raw_data))
    # ---> 28 assert np.allclose(u, u_orig)
    
    # AssertionError: 

    It definitely could have something to do with being a view though, but I'm not particularly familiar with recarrays

  4. ivirshup commented on Apr 15, 2019

    @ivirshup
    MemberAuthor

    I can finally get this to (not) work with random data:

    Slightly different, less cut down version
    a = sc.AnnData(np.random.random((1000, 1000)))
    b = sc.AnnData(np.random.random((1000, 1000)))
    
    sc.pp.pca(a)
    b.obsm["X_pca"] = a.obsm["X_pca"] + 1  # Error does not occur with `np.dot` or `+ 0`
    # Could also have done sc.pp.pca(b) and gotten error
    
    umap = UMAP()
    u1 = umap.fit_transform(a.obsm["X_pca"])
    u1_orig = u1.copy()
    print(joblib.hash(u1))
    print(joblib.hash(umap.embedding_))
    assert np.allclose(u1_orig, umap.embedding_)
    print(joblib.hash(u1))
    u2 = umap.transform(b.obsm["X_pca"])
    print(joblib.hash(u1))
    assert np.allclose(u1_orig, umap.embedding_)
    # 073bd434de1d0aa7c0410dc622af0184
    # 073bd434de1d0aa7c0410dc622af0184
    # 073bd434de1d0aa7c0410dc622af0184
    # 16613dd24c4b22aa1d4dbf931f492c5f
    # ---------------------------------------------------------------------------
    # AssertionError                            Traceback (most recent call last)
    # <ipython-input-160-f5b701ce789e> in <module>
    #      16 u2 = umap.transform(b.obsm["X_pca"])
    #      17 print(joblib.hash(u1))
    # ---> 18 assert np.allclose(u1_orig, umap.embedding_)
    
    # AssertionError: 

    Edit: Cut down slightly more:

    a = sc.AnnData(np.random.random((1000, 1000)))
    
    a.obsm["X_pca"] = np.random.random((1000, 50))
    bpca = a.obsm["X_pca"] + 1
    
    umap = UMAP()
    u1 = umap.fit_transform(a.obsm["X_pca"])
    u1_orig = u1.copy()
    print(joblib.hash(u1))
    print(joblib.hash(umap.embedding_))
    assert np.allclose(u1_orig, umap.embedding_)
    print(joblib.hash(u1))
    u2 = umap.transform(bpca)
    print(joblib.hash(u1))
    assert np.allclose(u1_orig, umap.embedding_)
    # 8160ae3f32e4cf8e27141d71b2bc4970
    # 8160ae3f32e4cf8e27141d71b2bc4970
    # 8160ae3f32e4cf8e27141d71b2bc4970
    # 99aeea40e6d08f9cf7b256511a701164
    # ---------------------------------------------------------------------------
    # AssertionError                            Traceback (most recent call last)
    # <ipython-input-170-a2cde0a33a6d> in <module>
    #      16 u2 = umap.transform(bpca)
    #      17 print(joblib.hash(u1))
    # ---> 18 assert np.allclose(u1_orig, umap.embedding_)
    
    # AssertionError: 
  5. ivirshup commented on Apr 15, 2019

    @ivirshup
    MemberAuthor

    After some blood, sweat, and tears I've managed to factor out AnnData entirely:

    Using a umap fit on a view of a recarray to transform any other array of the same size will modify the umap object internally. Any time you get some values from .obsm like adata.obsm["X_pca"] it is a view of a recarray, which is not obvious from how it's printed (thanks for pointing that out Alex!). Here's a little example:

    import numpy as np
    import joblib
    from umap import UMAP
    
    r = np.recarray((1000,), dtype=[("X", "<f8", (50,))])
    r["X"] = np.random.random((1000, 50))
    
    a = np.random.random((1000, 50))
    
    umap = UMAP()
    u1 = umap.fit_transform(r["X"])
    u1_orig = u1.copy()
    assert np.allclose(u1_orig, umap.embedding_)
    print(joblib.hash(u1))
    u2 = umap.transform(a)
    print(joblib.hash(u1))
    assert np.allclose(u1_orig, umap.embedding_)

    I'll go open an issue for UMAP now.

  6. falexwolf commented on Apr 16, 2019

    @falexwolf
    Member

    I can imagine that this was a lot of blood, sweat, and tears...

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