scrna5/6 Jupyter Notebook lamindata

Train a machine learning model on a collection#

Here, we iterate over the artifacts within a collection to train a machine learning model at scale.

import lamindb as ln
import anndata as ad
import numpy as np
馃挕 connected lamindb: testuser1/test-scrna
ln.settings.transform.stem_uid = "Qr1kIHvK506r"
ln.settings.transform.version = "1"
ln.track()
馃挕 notebook imports: anndata==0.9.2 lamindb==0.69.9 numpy==1.26.4 torch==2.2.2
馃挕 saved: Transform(uid='Qr1kIHvK506r5zKv', name='Train a machine learning model on a collection', key='scrna5', version='1', type='notebook', updated_at=2024-04-10 17:53:24 UTC, created_by_id=1)
馃挕 saved: Run(uid='1MHBxtU1Jk50aLXuZnhR', transform_id=5, created_by_id=1)

Query our collection:

collection = ln.Collection.filter(
    name="My versioned scRNA-seq collection", version="2"
).one()
collection.describe()
Hide code cell output
Collection(uid='pmqiGV7fNOJTWI04vw29', name='My versioned scRNA-seq collection', version='2', hash='HNR3VFV60_yqRnUka11E', visibility=1, updated_at=2024-04-10 17:53:03 UTC)

Provenance:
  馃搸 transform: Transform(uid='ManDYgmftZ8C5zKv', name='Standardize and append a batch of data', key='scrna2', version='1', type='notebook', updated_at=2024-04-10 17:52:44 UTC, created_by_id=1)
  馃搸 run: Run(uid='DvJwXOir8J9LgGl9PYAt', started_at=2024-04-10 17:52:44 UTC, is_consecutive=True, transform_id=2, created_by_id=1)
  馃搸 created_by: User(uid='DzTjkKse', handle='testuser1', name='Test User1', updated_at=2024-04-10 17:50:52 UTC)
  馃搸 input_of (core.Run): ['2024-04-10 17:53:14 UTC']
Features:
  var: FeatureSet(uid='CPlkkc63hVnZSKRWgRe0', n=36508, type='number', registry='bionty.Gene', hash='b5NMddLHEyZqn-vSYvBI', updated_at=2024-04-10 17:53:01 UTC, created_by_id=1)
    'MIR1302-2HG', 'FAM138A', 'OR4F5', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'OR4F29', 'None', 'OR4F16', 'None', 'LINC01409', 'FAM87B', 'LINC01128', 'LINC00115', 'FAM41C', 'None', ...
  obs: FeatureSet(uid='Ca5PrYB3AOm1piIwUIES', n=4, registry='core.Feature', hash='8gDo0ILt6wrOfQFp6okl', updated_at=2024-04-10 17:52:37 UTC, created_by_id=1)
    馃敆 donor (12, core.ULabel): 'D496', '621B', 'A29', 'A36', 'A35', '637C', 'A52', 'A37', 'D503', '640C', ...
    馃敆 tissue (17, bionty.Tissue): 'blood', 'thoracic lymph node', 'spleen', 'lung', 'mesenteric lymph node', 'lamina propria', 'liver', 'jejunal epithelium', 'omentum', 'bone marrow', ...
    馃敆 cell_type (40, bionty.CellType): 'dendritic cell', 'effector memory CD4-positive, alpha-beta T cell, terminally differentiated', 'cytotoxic T cell', 'CD8-positive, CD25-positive, alpha-beta regulatory T cell', 'CD14-positive, CD16-negative classical monocyte', 'CD38-positive naive B cell', 'B cell, CD19-positive', 'CD4-positive, alpha-beta T cell', 'classical monocyte', 'T follicular helper cell', ...
    馃敆 assay (3, bionty.ExperimentalFactor): '10x 3' v3', '10x 5' v2', '10x 5' v1'
Labels:
  馃搸 tissues (17, bionty.Tissue): 'blood', 'thoracic lymph node', 'spleen', 'lung', 'mesenteric lymph node', 'lamina propria', 'liver', 'jejunal epithelium', 'omentum', 'bone marrow', ...
  馃搸 cell_types (40, bionty.CellType): 'dendritic cell', 'effector memory CD4-positive, alpha-beta T cell, terminally differentiated', 'cytotoxic T cell', 'CD8-positive, CD25-positive, alpha-beta regulatory T cell', 'CD14-positive, CD16-negative classical monocyte', 'CD38-positive naive B cell', 'B cell, CD19-positive', 'CD4-positive, alpha-beta T cell', 'classical monocyte', 'T follicular helper cell', ...
  馃搸 experimental_factors (3, bionty.ExperimentalFactor): '10x 3' v3', '10x 5' v2', '10x 5' v1'
  馃搸 ulabels (12, core.ULabel): 'D496', '621B', 'A29', 'A36', 'A35', '637C', 'A52', 'A37', 'D503', '640C', ...

Create a map-style dataset#

Let us create a map-style dataset using using mapped(): a MappedCollection. This is what, for example, the PyTorch DataLoader expects as an input.

Under-the-hood, it performs a virtual inner join of the features of the underlying AnnData objects and thus allows to work with very large collections.

You can either perform a virtual inner join:

with collection.mapped(label_keys=["cell_type"], join="inner") as dataset:
    print(len(dataset.var_joint))
749

Or a virtual outer join:

dataset = collection.mapped(label_keys=["cell_type"], join="outer")
len(dataset.var_joint)
36508

This is compatible with a PyTorch DataLoader because it implements __getitem__ over a list of backed AnnData objects. The 5th cell in the collection can be accessed like:

dataset[5]
Hide code cell output
{'x': array([ 0.   ,  0.   ,  0.   , ...,  0.   ,  0.   , -0.456], dtype=float32),
 '_storage_idx': 0,
 'cell_type': 25}

The labels are encoded into integers:

dataset.encoders
Hide code cell output
{'cell_type': {'T follicular helper cell': 0,
  'mast cell': 1,
  'naive thymus-derived CD4-positive, alpha-beta T cell': 2,
  'effector memory CD4-positive, alpha-beta T cell': 3,
  'gamma-delta T cell': 4,
  'CD4-positive, alpha-beta T cell': 5,
  'conventional dendritic cell': 6,
  'CD14-positive, CD16-negative classical monocyte': 7,
  'dendritic cell, human': 8,
  'plasmacytoid dendritic cell': 9,
  'mucosal invariant T cell': 10,
  'group 3 innate lymphoid cell': 11,
  'animal cell': 12,
  'memory B cell': 13,
  'lymphocyte': 14,
  'germinal center B cell': 15,
  'CD8-positive, alpha-beta memory T cell': 16,
  'naive B cell': 17,
  'macrophage': 18,
  'plasma cell': 19,
  'megakaryocyte': 20,
  'alpha-beta T cell': 21,
  'classical monocyte': 22,
  'non-classical monocyte': 23,
  'dendritic cell': 24,
  'cytotoxic T cell': 25,
  'CD38-positive naive B cell': 26,
  'B cell, CD19-positive': 27,
  'naive thymus-derived CD8-positive, alpha-beta T cell': 28,
  'CD8-positive, CD25-positive, alpha-beta regulatory T cell': 29,
  'CD16-negative, CD56-bright natural killer cell, human': 30,
  'regulatory T cell': 31,
  'plasmablast': 32,
  'effector memory CD4-positive, alpha-beta T cell, terminally differentiated': 33,
  'alveolar macrophage': 34,
  'CD16-positive, CD56-dim natural killer cell, human': 35,
  'progenitor cell': 36,
  'effector memory CD8-positive, alpha-beta T cell, terminally differentiated': 37,
  'CD8-positive, alpha-beta memory T cell, CD45RO-positive': 38,
  'CD4-positive helper T cell': 39}}

Create a pytorch DataLoader#

Let us use a weighted sampler:

from torch.utils.data import DataLoader, WeightedRandomSampler

# label_key for weight doesn't have to be in labels on init
sampler = WeightedRandomSampler(
    weights=dataset.get_label_weights("cell_type"), num_samples=len(dataset)
)
dataloader = DataLoader(dataset, batch_size=128, sampler=sampler)

We can now iterate through the data loader:

for batch in dataloader:
    pass

Close the connections in MappedCollection:

dataset.close()
In practice, use a context manager
with collection.mapped(label_keys=["cell_type"]) as dataset:
    sampler = WeightedRandomSampler(
        weights=dataset.get_label_weights("cell_type"), num_samples=len(dataset)
    )
    dataloader = DataLoader(dataset, batch_size=128, sampler=sampler)
    for batch in dataloader:
        pass