Iteratively train an ML model on a dataset#
In the previous tutorial, we loaded an entire dataset into memory to perform a simple analysis.
Here, weβll iterate over the files within the dataset, to train an ML model.
import lamindb as ln
import anndata as ad
import numpy as np
π‘ loaded instance: testuser1/test-scrna (lamindb 0.56a1)
ln.track()
π‘ notebook imports: anndata==0.9.2 lamindb==0.56a1 numpy==1.25.2 scvi-tools==1.0.4
π‘ Transform(id=5, uid='Qr1kIHvK506rz8', name='Iteratively train an ML model on a dataset', short_name='scrna5', version='0', type=notebook, updated_at=2023-10-16 21:48:20, created_by_id=1)
π‘ Run(id=5, uid='W2pBST5UpRtEsWPgpTEn', run_at=2023-10-16 21:48:20, transform_id=5, created_by_id=1)
Setup#
dataset_v2 = ln.Dataset.filter(name="My versioned scRNA-seq dataset", version="2").one()
dataset_v2
Dataset(id=2, uid='PUwAqZ7C9c7EBQ7f0IgN', name='My versioned scRNA-seq dataset', version='2', hash='JNjc88f22TLVPJHdgo7X', updated_at=2023-10-16 21:47:46, transform_id=2, run_id=2, initial_version_id=1, created_by_id=1)
We import scvi-tools.
import scvi
Show code cell output
/opt/hostedtoolcache/Python/3.9.18/x64/lib/python3.9/site-packages/scvi/_settings.py:63: UserWarning: Since v1.0.0, scvi-tools no longer uses a random seed by default. Run `scvi.settings.seed = 0` to reproduce results from previous versions.
self.seed = seed
/opt/hostedtoolcache/Python/3.9.18/x64/lib/python3.9/site-packages/scvi/_settings.py:70: UserWarning: Setting `dl_pin_memory_gpu_training` is deprecated in v1.0 and will be removed in v1.1. Please pass in `pin_memory` to the data loaders instead.
self.dl_pin_memory_gpu_training = (
Similar to what we did in the previous tutorial, we could load the entire dataset into memory and train a model in 4 lines of code.
How would this look like?
data_train = dataset_v2.load(join="inner")
scvi.model.SCVI.setup_anndata(data_train)
vae = scvi.model.SCVI(data_train)
vae.train(max_epochs=1) # we use max_epochs=1 to be able to run it on CI
Let us instead load all file records:
file1, file2 = dataset_v2.files.list()
Weβd like some context on what the first file contains and where itβs from:
file1.describe()
file1.view_flow()
Show code cell output
File(id=1, uid='MpmFBPjOegAuuyRzbGAq', suffix='.h5ad', accessor='AnnData', description='Conde22', size=57615999, hash='6Hu1BywwK6bfIU2Dpku2xZ', hash_type='sha1-fl', updated_at=2023-10-16 21:47:05)
Provenance:
ποΈ storage: Storage(id=1, uid='bEvhinvc', root='/home/runner/work/lamin-usecases/lamin-usecases/docs/test-scrna', type='local', updated_at=2023-10-16 21:45:55, created_by_id=1)
π transform: Transform(id=1, uid='Nv48yAceNSh8z8', name='scRNA-seq', short_name='scrna', version='0', type='notebook', updated_at=2023-10-16 21:46:01, created_by_id=1)
π£ run: Run(id=1, uid='Tcf2JasApz9P8RE7gqna', run_at=2023-10-16 21:46:01, transform_id=1, created_by_id=1)
π€ created_by: User(id=1, uid='DzTjkKse', handle='testuser1', email='testuser1@lamin.ai', name='Test User1', updated_at=2023-10-16 21:45:55)
β¬οΈ input_of (core.Run): ['2023-10-16 21:47:14', '2023-10-16 21:47:54']
Features:
var: FeatureSet(id=1, uid='ISCdUu2vePwTzsv99UmG', n=36503, type='number', registry='bionty.Gene', hash='dnRexHCtxtmOU81_EpoJ', updated_at=2023-10-16 21:46:57, modality_id=1, 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(id=2, uid='AeMRCgTDsUFRNwXFlqD9', n=4, registry='core.Feature', hash='xPTyeKYm-_4RH5MEI97t', updated_at=2023-10-16 21:46:58, modality_id=2, created_by_id=1)
π cell_type (32, bionty.CellType): 'classical monocyte', 'T follicular helper cell', 'memory B cell', 'alveolar macrophage', 'naive thymus-derived CD4-positive, alpha-beta T cell', 'effector memory CD8-positive, alpha-beta T cell, terminally differentiated', 'alpha-beta T cell', 'CD4-positive helper T cell', 'naive thymus-derived CD8-positive, alpha-beta T cell', 'macrophage', ...
π assay (4, bionty.ExperimentalFactor): 'single-cell RNA sequencing', '10x 3' v3', '10x 5' v2', '10x 5' v1'
π tissue (17, bionty.Tissue): 'blood', 'thoracic lymph node', 'spleen', 'lung', 'mesenteric lymph node', 'lamina propria', 'liver', 'jejunal epithelium', 'omentum', 'bone marrow', ...
π donor (12, core.ULabel): 'D496', '621B', 'A29', 'A36', 'A35', '637C', 'A52', 'A37', 'D503', '640C', ...
Labels:
π·οΈ species (1, bionty.Species): 'human'
π·οΈ tissues (17, bionty.Tissue): 'blood', 'thoracic lymph node', 'spleen', 'lung', 'mesenteric lymph node', 'lamina propria', 'liver', 'jejunal epithelium', 'omentum', 'bone marrow', ...
π·οΈ cell_types (32, bionty.CellType): 'classical monocyte', 'T follicular helper cell', 'memory B cell', 'alveolar macrophage', 'naive thymus-derived CD4-positive, alpha-beta T cell', 'effector memory CD8-positive, alpha-beta T cell, terminally differentiated', 'alpha-beta T cell', 'CD4-positive helper T cell', 'naive thymus-derived CD8-positive, alpha-beta T cell', 'macrophage', ...
π·οΈ experimental_factors (4, bionty.ExperimentalFactor): 'single-cell RNA sequencing', '10x 3' v3', '10x 5' v2', '10x 5' v1'
π·οΈ ulabels (12, core.ULabel): 'D496', '621B', 'A29', 'A36', 'A35', '637C', 'A52', 'A37', 'D503', '640C', ...
Weβll need to make a decision on the features that we want to use for training the model.
Because each file is validated, theyβre all indexed by ensembl_gene_id
in the var
slot of AnnData.
shared_genes = file1.features["var"] & file2.features["var"]
shared_genes_ensembl = shared_genes.list("ensembl_gene_id")
Train the model#
Let us load the first file into memory:
data_train1 = file1.load().raw[:, shared_genes_ensembl].to_adata()
data_train1
AnnData object with n_obs Γ n_vars = 1648 Γ 749
obs: 'donor', 'tissue', 'cell_type', 'assay'
var: 'feature_name', 'feature_reference', 'feature_biotype'
uns: 'cell_type_ontology_term_id_colors', 'default_embedding', 'schema_version', 'title'
obsm: 'X_umap'
Train the model on this first file:
scvi.model.SCVI.setup_anndata(data_train1)
vae = scvi.model.SCVI(data_train1)
vae.train(max_epochs=1) # we use max_epochs=1 to run it on CI
vae.save("saved_models/scvi1")
Show code cell output
2023-10-16 21:48:27,373:INFO - Unable to initialize backend 'cuda': module 'jaxlib.xla_extension' has no attribute 'GpuAllocatorConfig'
2023-10-16 21:48:27,377:INFO - Unable to initialize backend 'rocm': module 'jaxlib.xla_extension' has no attribute 'GpuAllocatorConfig'
2023-10-16 21:48:27,380:INFO - Unable to initialize backend 'tpu': INTERNAL: Failed to open libtpu.so: libtpu.so: cannot open shared object file: No such file or directory
INFO: GPU available: False, used: False
2023-10-16 21:48:27,715:INFO - GPU available: False, used: False
INFO: TPU available: False, using: 0 TPU cores
2023-10-16 21:48:27,719:INFO - TPU available: False, using: 0 TPU cores
INFO: IPU available: False, using: 0 IPUs
2023-10-16 21:48:27,721:INFO - IPU available: False, using: 0 IPUs
INFO: HPU available: False, using: 0 HPUs
2023-10-16 21:48:27,723:INFO - HPU available: False, using: 0 HPUs
Training: 0%| | 0/1 [00:00<?, ?it/s]
Epoch 1/1: 0%| | 0/1 [00:00<?, ?it/s]
Epoch 1/1: 100%|ββββββββββ| 1/1 [00:00<00:00, 2.62it/s]
Epoch 1/1: 100%|ββββββββββ| 1/1 [00:00<00:00, 2.62it/s, v_num=1, train_loss_step=1.03e+3, train_loss_epoch=1.09e+3]
INFO: `Trainer.fit` stopped: `max_epochs=1` reached.
2023-10-16 21:48:28,142:INFO - `Trainer.fit` stopped: `max_epochs=1` reached.
Epoch 1/1: 100%|ββββββββββ| 1/1 [00:00<00:00, 2.50it/s, v_num=1, train_loss_step=1.03e+3, train_loss_epoch=1.09e+3]
Load the second file and resume training the model:
data_train2 = file2.load().raw[:, shared_genes_ensembl].to_adata()
vae = scvi.model.SCVI.load("saved_models/scvi1", data_train2)
vae.train(max_epochs=1)
vae.save("saved_models/scvi1", overwrite=True)
Show code cell output
INFO
File saved_models/scvi1/model.pt already downloaded
/opt/hostedtoolcache/Python/3.9.18/x64/lib/python3.9/site-packages/scvi/data/fields/_base_field.py:64: UserWarning: adata.X does not contain unnormalized count data. Are you sure this is what you want?
self.validate_field(adata)
INFO: GPU available: False, used: False
2023-10-16 21:48:28,306:INFO - GPU available: False, used: False
INFO: TPU available: False, using: 0 TPU cores
2023-10-16 21:48:28,308:INFO - TPU available: False, using: 0 TPU cores
INFO: IPU available: False, using: 0 IPUs
2023-10-16 21:48:28,310:INFO - IPU available: False, using: 0 IPUs
INFO: HPU available: False, using: 0 HPUs
2023-10-16 21:48:28,312:INFO - HPU available: False, using: 0 HPUs
/opt/hostedtoolcache/Python/3.9.18/x64/lib/python3.9/site-packages/lightning/pytorch/loops/fit_loop.py:281: PossibleUserWarning: The number of training batches (1) is smaller than the logging interval Trainer(log_every_n_steps=10). Set a lower value for log_every_n_steps if you want to see logs for the training epoch.
rank_zero_warn(
Training: 0%| | 0/1 [00:00<?, ?it/s]
Epoch 1/1: 0%| | 0/1 [00:00<?, ?it/s]
/opt/hostedtoolcache/Python/3.9.18/x64/lib/python3.9/site-packages/scvi/module/_vae.py:477: UserWarning: The value argument must be within the support of the distribution
reconst_loss = -generative_outputs["px"].log_prob(x).sum(-1)
Epoch 1/1: 100%|ββββββββββ| 1/1 [00:00<00:00, 34.74it/s, v_num=1, train_loss_step=820, train_loss_epoch=820]
INFO: `Trainer.fit` stopped: `max_epochs=1` reached.
2023-10-16 21:48:28,376:INFO - `Trainer.fit` stopped: `max_epochs=1` reached.
Epoch 1/1: 100%|ββββββββββ| 1/1 [00:00<00:00, 21.42it/s, v_num=1, train_loss_step=820, train_loss_epoch=820]
Save the model#
weights = ln.File("saved_models/scvi1/model.pt", description="My trained model")
weights.save()
Save latent representation as a new dataset#
latent1 = vae.get_latent_representation(data_train1)
latent2 = vae.get_latent_representation(data_train2)
adata_latent1 = ad.AnnData(X=latent1, obs=data_train1.obs)
adata_latent2 = ad.AnnData(X=latent2, obs=data_train2.obs)
INFO
Input AnnData not setup with scvi-tools. attempting to transfer AnnData setup
Because the latent representation is low-dimensional, we can typically fit very high number of observations into memory.
Hence, letβs store it as a concatenated adata.
adata_latent = ad.concat([adata_latent1, adata_latent2])
dataset_v2_latent = ln.Dataset(
adata_latent,
name="Latent representation of scRNA-seq dataset v2",
description="For the original data, see dataset T5x0SkRJNviE0jYGbJKt",
)
dataset_v2_latent.save()
Let us look at the data flow:
dataset_v2_latent.view_flow()
Compare this with the model:
weights.view_flow()
Annotate with labels:
dataset_v2_latent.labels.add_from(dataset_v2)
dataset_v2_latent.describe()
Dataset(id=3, uid='jYMFlK9mNGmFDeil1JMv', name='Latent representation of scRNA-seq dataset v2', description='For the original data, see dataset T5x0SkRJNviE0jYGbJKt', hash='1iz3mtUQx29dqxHtnJnY1A', updated_at=2023-10-16 21:48:28)
Provenance:
π« transform: Transform(id=5, uid='Qr1kIHvK506rz8', name='Iteratively train an ML model on a dataset', short_name='scrna5', version='0', type=notebook, updated_at=2023-10-16 21:48:20, created_by_id=1)
π£ run: Run(id=5, uid='W2pBST5UpRtEsWPgpTEn', run_at=2023-10-16 21:48:20, transform_id=5, created_by_id=1)
π file: File(id=5, uid='jYMFlK9mNGmFDeil1JMv', suffix='.h5ad', accessor='AnnData', description='See dataset jYMFlK9mNGmFDeil1JMv', size=220226, hash='1iz3mtUQx29dqxHtnJnY1A', hash_type='md5', updated_at=2023-10-16 21:48:28, storage_id=1, transform_id=5, run_id=5, created_by_id=1)
π€ created_by: User(id=1, uid='DzTjkKse', handle='testuser1', email='testuser1@lamin.ai', name='Test User1', updated_at=2023-10-16 21:45:55)
Features:
external: FeatureSet(id=10, uid='7QNG1GjLqcCsXb5Z10rf', n=5, registry='core.Feature', hash='Rc0k4cM-byrLP221ZkvF', updated_at=2023-10-16 21:48:29, modality_id=2, created_by_id=1)
π cell_type (39, bionty.CellType): 'classical monocyte', 'T follicular helper cell', 'memory B cell', 'alveolar macrophage', 'naive thymus-derived CD4-positive, alpha-beta T cell', 'effector memory CD8-positive, alpha-beta T cell, terminally differentiated', 'alpha-beta T cell', 'CD4-positive helper T cell', 'naive thymus-derived CD8-positive, alpha-beta T cell', 'macrophage', ...
π assay (4, bionty.ExperimentalFactor): '10x 3' v3', '10x 5' v2', '10x 5' v1', 'single-cell RNA sequencing'
π tissue (17, bionty.Tissue): 'blood', 'thoracic lymph node', 'spleen', 'lung', 'mesenteric lymph node', 'lamina propria', 'liver', 'jejunal epithelium', 'omentum', 'bone marrow', ...
π species (1, bionty.Species): 'human'
π donor (12, core.ULabel): 'D496', '621B', 'A29', 'A36', 'A35', '637C', 'A52', 'A37', 'D503', '640C', ...
Labels:
π·οΈ species (1, bionty.Species): 'human'
π·οΈ tissues (17, bionty.Tissue): 'blood', 'thoracic lymph node', 'spleen', 'lung', 'mesenteric lymph node', 'lamina propria', 'liver', 'jejunal epithelium', 'omentum', 'bone marrow', ...
π·οΈ cell_types (39, bionty.CellType): 'classical monocyte', 'T follicular helper cell', 'memory B cell', 'alveolar macrophage', 'naive thymus-derived CD4-positive, alpha-beta T cell', 'effector memory CD8-positive, alpha-beta T cell, terminally differentiated', 'alpha-beta T cell', 'CD4-positive helper T cell', 'naive thymus-derived CD8-positive, alpha-beta T cell', 'macrophage', ...
π·οΈ experimental_factors (4, bionty.ExperimentalFactor): '10x 3' v3', '10x 5' v2', '10x 5' v1', 'single-cell RNA sequencing'
π·οΈ ulabels (12, core.ULabel): 'D496', '621B', 'A29', 'A36', 'A35', '637C', 'A52', 'A37', 'D503', '640C', ...
# clean up test instance
!lamin delete --force test-scrna
!rm -r ./test-scrna
π‘ deleting instance testuser1/test-scrna
β
deleted instance settings file: /home/runner/.lamin/instance--testuser1--test-scrna.env
β
instance cache deleted
β
deleted '.lndb' sqlite file
β consider manually deleting your stored data: /home/runner/work/lamin-usecases/lamin-usecases/docs/test-scrna