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.70.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-24 12:50:13 UTC, created_by_id=1)
馃挕 saved: Run(uid='sQ07dCGe5aqpqtilTlZI', 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()
Show code cell output
Collection(uid='LlHEgJ7jHU4exSjxjPg1', name='My versioned scRNA-seq collection', version='2', hash='HNR3VFV60_yqRnUka11E', visibility=1, updated_at=2024-04-24 12:49:49 UTC)
Provenance:
馃搸 transform: Transform(uid='ManDYgmftZ8C5zKv', name='Standardize and append a batch of data', key='scrna2', version='1', type='notebook')
馃搸 run: Run(uid='SPE6427CHMPbSOxiYsOy', started_at=2024-04-24 12:49:25 UTC, is_consecutive=True)
馃搸 created_by: User(uid='DzTjkKse', handle='testuser1', name='Test User1')
馃搸 input_of (core.Run): ['2024-04-24 12:50:00 UTC']
Features:
var: FeatureSet(uid='eVWEmRByUQlHAKAJGrYk', n=36508, type='number', registry='bionty.Gene')
'MYD88', 'C1QTNF9B', 'CLDN6', 'CDC42SE1', 'ADAMTS13', 'MAD1L1', 'RAB40B', 'YIPF3', 'FN3K', 'RASSF3-DT', 'EXOSC6', 'LINC01394', 'APOO', 'AGTR2', 'LINC02640', 'CEP70', 'DTWD2', 'COL15A1', 'PRR22', 'SH2D6', ...
obs: FeatureSet(uid='aPDq1l9j7zKZxKKt2sZV', n=4, registry='core.Feature')
馃敆 donor (12, core.ULabel): '621B', '637C', 'A37', '640C', 'A35', 'A36', 'A52', 'A31', 'D496', 'D503', ...
馃敆 tissue (17, bionty.Tissue): 'lamina propria', 'thoracic lymph node', 'jejunal epithelium', 'omentum', 'duodenum', 'caecum', 'blood', 'ileum', 'thymus', 'bone marrow', ...
馃敆 cell_type (40, bionty.CellType): 'naive thymus-derived CD8-positive, alpha-beta T cell', 'CD4-positive helper T cell', 'dendritic cell', 'effector memory CD4-positive, alpha-beta T cell, terminally differentiated', 'effector memory CD4-positive, alpha-beta T cell', 'B cell, CD19-positive', 'CD16-positive, CD56-dim natural killer cell, human', 'animal cell', 'CD8-positive, alpha-beta memory T cell', 'CD8-positive, CD25-positive, alpha-beta regulatory T cell', ...
馃敆 assay (3, bionty.ExperimentalFactor): '10x 5' v2', '10x 3' v3', '10x 5' v1'
Labels:
馃搸 tissues (17, bionty.Tissue): 'lamina propria', 'thoracic lymph node', 'jejunal epithelium', 'omentum', 'duodenum', 'caecum', 'blood', 'ileum', 'thymus', 'bone marrow', ...
馃搸 cell_types (40, bionty.CellType): 'naive thymus-derived CD8-positive, alpha-beta T cell', 'CD4-positive helper T cell', 'dendritic cell', 'effector memory CD4-positive, alpha-beta T cell, terminally differentiated', 'effector memory CD4-positive, alpha-beta T cell', 'B cell, CD19-positive', 'CD16-positive, CD56-dim natural killer cell, human', 'animal cell', 'CD8-positive, alpha-beta memory T cell', 'CD8-positive, CD25-positive, alpha-beta regulatory T cell', ...
馃搸 experimental_factors (3, bionty.ExperimentalFactor): '10x 5' v2', '10x 3' v3', '10x 5' v1'
馃搸 ulabels (12, core.ULabel): '621B', '637C', 'A37', '640C', 'A35', 'A36', 'A52', 'A31', 'D496', 'D503', ...
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]
Show code cell output
{'X': array([ 0. , 0. , 0. , ..., 0. , 0. , -0.456], dtype=float32),
'_store_idx': 0,
'cell_type': 26}
The labels
are encoded into integers:
dataset.encoders
Show code cell output
{'cell_type': {'naive thymus-derived CD8-positive, alpha-beta T cell': 0,
'CD4-positive helper T cell': 1,
'dendritic cell': 2,
'effector memory CD4-positive, alpha-beta T cell, terminally differentiated': 3,
'effector memory CD4-positive, alpha-beta T cell': 4,
'B cell, CD19-positive': 5,
'CD16-positive, CD56-dim natural killer cell, human': 6,
'animal cell': 7,
'CD8-positive, alpha-beta memory T cell': 8,
'CD8-positive, CD25-positive, alpha-beta regulatory T cell': 9,
'CD38-positive naive B cell': 10,
'alveolar macrophage': 11,
'lymphocyte': 12,
'naive thymus-derived CD4-positive, alpha-beta T cell': 13,
'memory B cell': 14,
'T follicular helper cell': 15,
'plasmacytoid dendritic cell': 16,
'dendritic cell, human': 17,
'conventional dendritic cell': 18,
'group 3 innate lymphoid cell': 19,
'gamma-delta T cell': 20,
'non-classical monocyte': 21,
'macrophage': 22,
'plasmablast': 23,
'effector memory CD8-positive, alpha-beta T cell, terminally differentiated': 24,
'regulatory T cell': 25,
'cytotoxic T cell': 26,
'CD4-positive, alpha-beta T cell': 27,
'CD8-positive, alpha-beta memory T cell, CD45RO-positive': 28,
'plasma cell': 29,
'progenitor cell': 30,
'CD16-negative, CD56-bright natural killer cell, human': 31,
'alpha-beta T cell': 32,
'germinal center B cell': 33,
'naive B cell': 34,
'classical monocyte': 35,
'mast cell': 36,
'megakaryocyte': 37,
'mucosal invariant T cell': 38,
'CD14-positive, CD16-negative classical monocyte': 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(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