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
💡 connected lamindb: testuser1/test-scrna
ln.settings.transform.stem_uid = "Qr1kIHvK506r"
ln.settings.transform.version = "1"
ln.track()
💡 notebook imports: lamindb==0.74.3 torch==2.4.0
💡 saved: Transform(uid='Qr1kIHvK506r5zKv', version='1', name='Train a machine learning model on a collection', key='scrna5', type='notebook', created_by_id=1, updated_at='2024-07-26 12:22:50 UTC')
💡 saved: Run(uid='mpUCwZ8RKqPqxw7q9O3B', transform_id=5, created_by_id=1)
Run(uid='mpUCwZ8RKqPqxw7q9O3B', started_at='2024-07-26 12:22:50 UTC', is_consecutive=True, 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='7hRDhzTTUWLHntihz8tr', version='2', name='My versioned scRNA-seq collection', hash='Umjxg4HR1wkZqKROsyz1', visibility=1, updated_at='2024-07-26 12:22:23 UTC')
  Provenance
    .created_by = 'testuser1'
    .transform = 'Standardize and append a batch of data'
    .run = '2024-07-26 12:21:55 UTC'
    .input_of = ["'2024-07-26 12:22:33 UTC'"]
  Feature sets
    'obs' = 'donor', 'tissue', 'cell_type', 'assay'
    'var' = 'MIR1302-2HG', 'FAM138A', 'OR4F5', 'None', 'OR4F29', 'OR4F16', 'LINC01409', 'FAM87B', 'LINC01128', 'LINC00115', 'FAM41C'

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(obs_keys=["cell_type"], join="inner") as dataset:
    print(len(dataset.var_joint))
749

Or a virtual outer join:

dataset = collection.mapped(obs_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),
 '_store_idx': 0,
 'cell_type': 9}

The labels are encoded into integers:

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

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(obs_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