Repository files navigation

TissueFormer: A Multi-Modal Foundation Model for Spatial Biology

TissueFormer is pretrained over 1.2K paired tissue slides each of which includes a haematoxylin and eosin (H&E)-stained whole-slide image and its corresponding spatial transcriptomic profile. From these tissue slides, we derive 17 million image-expression pairs and a unified gene panel that contains over 20K protein-coding genes for pretraining. At inference time, the model can be applied to cross-modality generation (e.g., predict gene expression at cellular resolutions from histology images), predictive tasks at cell / region / slide levels, as well as analysis of intercellular communication and cell subtype identification.

Model Overview

image

The model is pretrained with a large corpus of spatial data ranging from diverse organs, species and health/disease states and can generalize to unseen tissues, organs, and species for prediction at cell, region and slide levels as well as informing spatial analysis and discovery.

image

Datasets

All datasets used for the training and evaluation of our model are publicly available. The HEST-1K can be accessed HuggingFace. The Xenium human breast tissue slides were included in HEST-1K. We used the data version released by the original paper in 10XGenomics. The dataset of human lung tissues with pulmonary fibrosis is deposited in the GEO database under accession number GSE250346.

Reproducing the Results

Please follow the steps below to reproduce the results and analysis performed in this study.

  1. Prerequisite

First of all, Anaconda or Miniconda is needed to run the commands in this guide. You can check if it is installed via running

 conda

If it is not installed, then run the following commands:

 wget https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Linux-x86_64.sh
chmod +x Anaconda3-2023.03-1-Linux-x86_64.sh
./Anaconda3-2023.03-1-Linux-x86_64.sh
vim ~/.bashrc
export PATH=/root/anaconda3/bin:$PATHsource~/.bashrc

Then clone this repository by running the following command in a new terminal:

 git clone https://github.com/uhlerlab/TissueFormer

Make sure you are in the root directory (i.e., TissueFormer/) by typing

cd TissueFormer

Create a new environment with the packages provided by environment.yml:

 conda env create -f environment.yml -n tissueformer
conda activate tissueformer
  1. Data preprocessing

We provide the instruction for using our data preprocessing pipeline.

  1. Training (pretraining and finetuning)

TissueFormer adopts two-stage curriculum learning for pretraining: the model was first trained with spot-resolution data (e.g., Visium slides) and further trained with cell-resolution data (e.g., Xenium slides). For applications, the pretrained TissueFormer can be directly applied to zero-shot predictions on new datasets or finetuned with new data. We provide the instruction for using our pipeline of pretraining and finetuning.

  1. Inference for prediction

After pretraining, TissueFormer is capable of handling various predictive tasks only using histology images of test samples. One typical task is cross-modality generation, i.e., predicting spatial gene expression from histology images. Furthermore, the pretrained model can be applied to predictions at different biological scales (cell-level, region-level, slide-level) from histology images. We provide the instruction for applying TissueFormer to predictions.

  1. Inference for analysis

Apart from predictive tasks, TissueFormer supports analysis of intercellular communication and cell subtying from histology images. For these, the pretrained model provides whole-slide cell-cell attention maps and cell-level embeddings for interpreting and analyzing the mechanism. We provide the instruction for applying TissueFormer to analysis.

  1. Visualization

All illustrative figures (Fig. 1 and Supplementary Fig. 1-2) in this study were made using Draw.io, PowerPoint and Adobe Illustrator.

Pointers for nonillustrative figures:

  • ./analysis/gene_exp_pred_visium.ipynb: Fig. 2, Supplementary Fig. 3-4
  • ./analysis/gene_exp_pred_xenium.ipynb: Fig. 3, Supplementary Fig. 5-7
  • ./analysis/diagnosis_pred_lung.ipynb: Fig. 4, Supplementary Fig. 8
  • ./analysis/analysis_lung_fibrosis.ipynb: Fig. 5, Supplementary Fig. 9-10
  • ./analysis/analysis_breast_tumor.ipynb: Supplementary Fig. 11

Apply TissueFormer to User-provided Datasets

Applying TissueFormer to any new dataset typically involves the following steps:

  1. Load preprocessed dataset
  2. Load pretrained model checkpoints
  3. Optional: finetune the model on new datasets
  4. Apply the model for prediction (e.g., predict gene expression from histology images)
  5. Apply the model for analysis (extract the cell embeddings and attention maps)

Application Demo 1

Here we use the test Xenium samples (TENX126, TENX123, TENX124, TENX121, TENX119, TENX118) as an example to demonstrate how to use our model on test data and reproduce the results.

  1. Load preprocessed dataset

One can download the preprocessed data from this Google Drive into a folder ./data

  1. Load pretrained model checkpoints

The same google drive repository contains the pretrained model checkpoints and one can download them into a folder ./checkpoint.

  1. Apply the model for prediction

Then one can refer to ./prediction/main_evaluate_xenium.py and modify the directory paths storing the dataset, model checkpoint and results:

dir_path='./data/hest_data_xenium_protein_preprocess'pretrain_model_path='./checkpoint/ours_pretrain_xenium_sample+_small.pth'result_path=f'./result/gene_expression_prediction/{test_sample}'

After modifying the paths, one can run the following script to execute prediction on these test samples (the batch_size can be adjusted to balance the memory and time costs):

 python main_evaluate_xenium.py --domain_protocol sample --hvg_gene_tops 400 --method ours --gene_emb_dim 128 \
--enc1_hidden_channels 128 --enc2_hidden_channels 128 --enc1_num_layers_prop 2 --enc1_num_layers_mlp 2 --enc2_num_layers_mlp 1 \
--neighbor_num 1000 --batch_size 1000 --device 7

The prediction results are stored into the path ./result/gene_expression_prediction/.

  1. Visualization

The visualization code for our results (Fig. 3a, Supplementary Fig. 5) is provided in this demo1.

image

Application Demo 2

For applying TissueFormer to user-provided datasets, we provide a demo2 as an example. One can use this demo by replacing the dataset with one's own and following the instruction below.

First, one needs to specify the directory path storing the dataset and load the dataset that is split for training and test:

dir_path='/ewsc/wuqitian/lung_preprocess'meta_info=pd.read_csv("../../data/meta_info_lung.csv")
# train data can be used as the reference for in-context learning or for finetuning the modeltrain_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[:-1]
# test data for evaluationtest_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[-1:]
# create dataloadertrain_datasets=dataset_create(dir_path, train_samples)
train_dataloader=DataLoader(train_datasets, batch_size=1, shuffle=True)
test_datasets=dataset_create(dir_path, test_samples)
test_dataloader=DataLoader(test_datasets, batch_size=1, shuffle=False)

Second, load the pretrained model checkpoint (one can choose the pretrained model version):

pretrained_state_dict=torch.load('../../model_checkpoints/ours_pretrain_xenium_lung.pth') # one can choose the model versionencoder1_pretrained_dict= {k: vfork, vinpretrained_state_dict.items() ifk.startswith("encoder1.")}
model_state_dict=model_ours.state_dict()
encoder1_model_dict= {k: vfork, vinmodel_state_dict.items() ifk.startswith("encoder1.")}
fork, vinencoder1_pretrained_dict.items():
assert (kinencoder1_model_dict)
assert (v.size() ==encoder1_model_dict[k].size())
model_state_dict.update(encoder1_pretrained_dict)
model_ours.load_state_dict(model_state_dict)

Later on, one can use the model for prediction, analysis (extract cell-level embeddings and attentions) or finetuning the model with downstream labels by following the scripts in demo2.

About

No description, website, or topics provided.

Resources

Stars

8 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

TissueFormer: A Multi-Modal Foundation Model for Spatial Biology

TissueFormer is pretrained over 1.2K paired tissue slides each of which includes a haematoxylin and eosin (H&E)-stained whole-slide image and its corresponding spatial transcriptomic profile. From these tissue slides, we derive 17 million image-expression pairs and a unified gene panel that contains over 20K protein-coding genes for pretraining. At inference time, the model can be applied to cross-modality generation (e.g., predict gene expression at cellular resolutions from histology images), predictive tasks at cell / region / slide levels, as well as analysis of intercellular communication and cell subtype identification.

Model Overview

image

The model is pretrained with a large corpus of spatial data ranging from diverse organs, species and health/disease states and can generalize to unseen tissues, organs, and species for prediction at cell, region and slide levels as well as informing spatial analysis and discovery.

image

Datasets

All datasets used for the training and evaluation of our model are publicly available. The HEST-1K can be accessed HuggingFace. The Xenium human breast tissue slides were included in HEST-1K. We used the data version released by the original paper in 10XGenomics. The dataset of human lung tissues with pulmonary fibrosis is deposited in the GEO database under accession number GSE250346.

Reproducing the Results

Please follow the steps below to reproduce the results and analysis performed in this study.

  1. Prerequisite

First of all, Anaconda or Miniconda is needed to run the commands in this guide. You can check if it is installed via running

 conda

If it is not installed, then run the following commands:

 wget https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Linux-x86_64.sh
chmod +x Anaconda3-2023.03-1-Linux-x86_64.sh
./Anaconda3-2023.03-1-Linux-x86_64.sh
vim ~/.bashrc
export PATH=/root/anaconda3/bin:$PATHsource~/.bashrc

Then clone this repository by running the following command in a new terminal:

 git clone https://github.com/uhlerlab/TissueFormer

Make sure you are in the root directory (i.e., TissueFormer/) by typing

cd TissueFormer

Create a new environment with the packages provided by environment.yml:

 conda env create -f environment.yml -n tissueformer
conda activate tissueformer
  1. Data preprocessing

We provide the instruction for using our data preprocessing pipeline.

  1. Training (pretraining and finetuning)

TissueFormer adopts two-stage curriculum learning for pretraining: the model was first trained with spot-resolution data (e.g., Visium slides) and further trained with cell-resolution data (e.g., Xenium slides). For applications, the pretrained TissueFormer can be directly applied to zero-shot predictions on new datasets or finetuned with new data. We provide the instruction for using our pipeline of pretraining and finetuning.

  1. Inference for prediction

After pretraining, TissueFormer is capable of handling various predictive tasks only using histology images of test samples. One typical task is cross-modality generation, i.e., predicting spatial gene expression from histology images. Furthermore, the pretrained model can be applied to predictions at different biological scales (cell-level, region-level, slide-level) from histology images. We provide the instruction for applying TissueFormer to predictions.

  1. Inference for analysis

Apart from predictive tasks, TissueFormer supports analysis of intercellular communication and cell subtying from histology images. For these, the pretrained model provides whole-slide cell-cell attention maps and cell-level embeddings for interpreting and analyzing the mechanism. We provide the instruction for applying TissueFormer to analysis.

  1. Visualization

All illustrative figures (Fig. 1 and Supplementary Fig. 1-2) in this study were made using Draw.io, PowerPoint and Adobe Illustrator.

Pointers for nonillustrative figures:

  • ./analysis/gene_exp_pred_visium.ipynb: Fig. 2, Supplementary Fig. 3-4
  • ./analysis/gene_exp_pred_xenium.ipynb: Fig. 3, Supplementary Fig. 5-7
  • ./analysis/diagnosis_pred_lung.ipynb: Fig. 4, Supplementary Fig. 8
  • ./analysis/analysis_lung_fibrosis.ipynb: Fig. 5, Supplementary Fig. 9-10
  • ./analysis/analysis_breast_tumor.ipynb: Supplementary Fig. 11

Apply TissueFormer to User-provided Datasets

Applying TissueFormer to any new dataset typically involves the following steps:

  1. Load preprocessed dataset
  2. Load pretrained model checkpoints
  3. Optional: finetune the model on new datasets
  4. Apply the model for prediction (e.g., predict gene expression from histology images)
  5. Apply the model for analysis (extract the cell embeddings and attention maps)

Application Demo 1

Here we use the test Xenium samples (TENX126, TENX123, TENX124, TENX121, TENX119, TENX118) as an example to demonstrate how to use our model on test data and reproduce the results.

  1. Load preprocessed dataset

One can download the preprocessed data from this Google Drive into a folder ./data

  1. Load pretrained model checkpoints

The same google drive repository contains the pretrained model checkpoints and one can download them into a folder ./checkpoint.

  1. Apply the model for prediction

Then one can refer to ./prediction/main_evaluate_xenium.py and modify the directory paths storing the dataset, model checkpoint and results:

dir_path='./data/hest_data_xenium_protein_preprocess'pretrain_model_path='./checkpoint/ours_pretrain_xenium_sample+_small.pth'result_path=f'./result/gene_expression_prediction/{test_sample}'

After modifying the paths, one can run the following script to execute prediction on these test samples (the batch_size can be adjusted to balance the memory and time costs):

 python main_evaluate_xenium.py --domain_protocol sample --hvg_gene_tops 400 --method ours --gene_emb_dim 128 \
--enc1_hidden_channels 128 --enc2_hidden_channels 128 --enc1_num_layers_prop 2 --enc1_num_layers_mlp 2 --enc2_num_layers_mlp 1 \
--neighbor_num 1000 --batch_size 1000 --device 7

The prediction results are stored into the path ./result/gene_expression_prediction/.

  1. Visualization

The visualization code for our results (Fig. 3a, Supplementary Fig. 5) is provided in this demo1.

image

Application Demo 2

For applying TissueFormer to user-provided datasets, we provide a demo2 as an example. One can use this demo by replacing the dataset with one's own and following the instruction below.

First, one needs to specify the directory path storing the dataset and load the dataset that is split for training and test:

dir_path='/ewsc/wuqitian/lung_preprocess'meta_info=pd.read_csv("../../data/meta_info_lung.csv")
# train data can be used as the reference for in-context learning or for finetuning the modeltrain_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[:-1]
# test data for evaluationtest_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[-1:]
# create dataloadertrain_datasets=dataset_create(dir_path, train_samples)
train_dataloader=DataLoader(train_datasets, batch_size=1, shuffle=True)
test_datasets=dataset_create(dir_path, test_samples)
test_dataloader=DataLoader(test_datasets, batch_size=1, shuffle=False)

Second, load the pretrained model checkpoint (one can choose the pretrained model version):

pretrained_state_dict=torch.load('../../model_checkpoints/ours_pretrain_xenium_lung.pth') # one can choose the model versionencoder1_pretrained_dict= {k: vfork, vinpretrained_state_dict.items() ifk.startswith("encoder1.")}
model_state_dict=model_ours.state_dict()
encoder1_model_dict= {k: vfork, vinmodel_state_dict.items() ifk.startswith("encoder1.")}
fork, vinencoder1_pretrained_dict.items():
assert (kinencoder1_model_dict)
assert (v.size() ==encoder1_model_dict[k].size())
model_state_dict.update(encoder1_pretrained_dict)
model_ours.load_state_dict(model_state_dict)

Later on, one can use the model for prediction, analysis (extract cell-level embeddings and attentions) or finetuning the model with downstream labels by following the scripts in demo2.

About

No description, website, or topics provided.

Resources

Stars

8 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

TissueFormer: A Multi-Modal Foundation Model for Spatial Biology

TissueFormer is pretrained over 1.2K paired tissue slides each of which includes a haematoxylin and eosin (H&E)-stained whole-slide image and its corresponding spatial transcriptomic profile. From these tissue slides, we derive 17 million image-expression pairs and a unified gene panel that contains over 20K protein-coding genes for pretraining. At inference time, the model can be applied to cross-modality generation (e.g., predict gene expression at cellular resolutions from histology images), predictive tasks at cell / region / slide levels, as well as analysis of intercellular communication and cell subtype identification.

Model Overview

image

The model is pretrained with a large corpus of spatial data ranging from diverse organs, species and health/disease states and can generalize to unseen tissues, organs, and species for prediction at cell, region and slide levels as well as informing spatial analysis and discovery.

image

Datasets

All datasets used for the training and evaluation of our model are publicly available. The HEST-1K can be accessed HuggingFace. The Xenium human breast tissue slides were included in HEST-1K. We used the data version released by the original paper in 10XGenomics. The dataset of human lung tissues with pulmonary fibrosis is deposited in the GEO database under accession number GSE250346.

Reproducing the Results

Please follow the steps below to reproduce the results and analysis performed in this study.

  1. Prerequisite

First of all, Anaconda or Miniconda is needed to run the commands in this guide. You can check if it is installed via running

 conda

If it is not installed, then run the following commands:

 wget https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Linux-x86_64.sh
chmod +x Anaconda3-2023.03-1-Linux-x86_64.sh
./Anaconda3-2023.03-1-Linux-x86_64.sh
vim ~/.bashrc
export PATH=/root/anaconda3/bin:$PATHsource~/.bashrc

Then clone this repository by running the following command in a new terminal:

 git clone https://github.com/uhlerlab/TissueFormer

Make sure you are in the root directory (i.e., TissueFormer/) by typing

cd TissueFormer

Create a new environment with the packages provided by environment.yml:

 conda env create -f environment.yml -n tissueformer
conda activate tissueformer
  1. Data preprocessing

We provide the instruction for using our data preprocessing pipeline.

  1. Training (pretraining and finetuning)

TissueFormer adopts two-stage curriculum learning for pretraining: the model was first trained with spot-resolution data (e.g., Visium slides) and further trained with cell-resolution data (e.g., Xenium slides). For applications, the pretrained TissueFormer can be directly applied to zero-shot predictions on new datasets or finetuned with new data. We provide the instruction for using our pipeline of pretraining and finetuning.

  1. Inference for prediction

After pretraining, TissueFormer is capable of handling various predictive tasks only using histology images of test samples. One typical task is cross-modality generation, i.e., predicting spatial gene expression from histology images. Furthermore, the pretrained model can be applied to predictions at different biological scales (cell-level, region-level, slide-level) from histology images. We provide the instruction for applying TissueFormer to predictions.

  1. Inference for analysis

Apart from predictive tasks, TissueFormer supports analysis of intercellular communication and cell subtying from histology images. For these, the pretrained model provides whole-slide cell-cell attention maps and cell-level embeddings for interpreting and analyzing the mechanism. We provide the instruction for applying TissueFormer to analysis.

  1. Visualization

All illustrative figures (Fig. 1 and Supplementary Fig. 1-2) in this study were made using Draw.io, PowerPoint and Adobe Illustrator.

Pointers for nonillustrative figures:

  • ./analysis/gene_exp_pred_visium.ipynb: Fig. 2, Supplementary Fig. 3-4
  • ./analysis/gene_exp_pred_xenium.ipynb: Fig. 3, Supplementary Fig. 5-7
  • ./analysis/diagnosis_pred_lung.ipynb: Fig. 4, Supplementary Fig. 8
  • ./analysis/analysis_lung_fibrosis.ipynb: Fig. 5, Supplementary Fig. 9-10
  • ./analysis/analysis_breast_tumor.ipynb: Supplementary Fig. 11

Apply TissueFormer to User-provided Datasets

Applying TissueFormer to any new dataset typically involves the following steps:

  1. Load preprocessed dataset
  2. Load pretrained model checkpoints
  3. Optional: finetune the model on new datasets
  4. Apply the model for prediction (e.g., predict gene expression from histology images)
  5. Apply the model for analysis (extract the cell embeddings and attention maps)

Application Demo 1

Here we use the test Xenium samples (TENX126, TENX123, TENX124, TENX121, TENX119, TENX118) as an example to demonstrate how to use our model on test data and reproduce the results.

  1. Load preprocessed dataset

One can download the preprocessed data from this Google Drive into a folder ./data

  1. Load pretrained model checkpoints

The same google drive repository contains the pretrained model checkpoints and one can download them into a folder ./checkpoint.

  1. Apply the model for prediction

Then one can refer to ./prediction/main_evaluate_xenium.py and modify the directory paths storing the dataset, model checkpoint and results:

dir_path='./data/hest_data_xenium_protein_preprocess'pretrain_model_path='./checkpoint/ours_pretrain_xenium_sample+_small.pth'result_path=f'./result/gene_expression_prediction/{test_sample}'

After modifying the paths, one can run the following script to execute prediction on these test samples (the batch_size can be adjusted to balance the memory and time costs):

 python main_evaluate_xenium.py --domain_protocol sample --hvg_gene_tops 400 --method ours --gene_emb_dim 128 \
--enc1_hidden_channels 128 --enc2_hidden_channels 128 --enc1_num_layers_prop 2 --enc1_num_layers_mlp 2 --enc2_num_layers_mlp 1 \
--neighbor_num 1000 --batch_size 1000 --device 7

The prediction results are stored into the path ./result/gene_expression_prediction/.

  1. Visualization

The visualization code for our results (Fig. 3a, Supplementary Fig. 5) is provided in this demo1.

image

Application Demo 2

For applying TissueFormer to user-provided datasets, we provide a demo2 as an example. One can use this demo by replacing the dataset with one's own and following the instruction below.

First, one needs to specify the directory path storing the dataset and load the dataset that is split for training and test:

dir_path='/ewsc/wuqitian/lung_preprocess'meta_info=pd.read_csv("../../data/meta_info_lung.csv")
# train data can be used as the reference for in-context learning or for finetuning the modeltrain_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[:-1]
# test data for evaluationtest_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[-1:]
# create dataloadertrain_datasets=dataset_create(dir_path, train_samples)
train_dataloader=DataLoader(train_datasets, batch_size=1, shuffle=True)
test_datasets=dataset_create(dir_path, test_samples)
test_dataloader=DataLoader(test_datasets, batch_size=1, shuffle=False)

Second, load the pretrained model checkpoint (one can choose the pretrained model version):

pretrained_state_dict=torch.load('../../model_checkpoints/ours_pretrain_xenium_lung.pth') # one can choose the model versionencoder1_pretrained_dict= {k: vfork, vinpretrained_state_dict.items() ifk.startswith("encoder1.")}
model_state_dict=model_ours.state_dict()
encoder1_model_dict= {k: vfork, vinmodel_state_dict.items() ifk.startswith("encoder1.")}
fork, vinencoder1_pretrained_dict.items():
assert (kinencoder1_model_dict)
assert (v.size() ==encoder1_model_dict[k].size())
model_state_dict.update(encoder1_pretrained_dict)
model_ours.load_state_dict(model_state_dict)

Later on, one can use the model for prediction, analysis (extract cell-level embeddings and attentions) or finetuning the model with downstream labels by following the scripts in demo2.

About

No description, website, or topics provided.

Resources

Stars

8 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

TissueFormer: A Multi-Modal Foundation Model for Spatial Biology

TissueFormer is pretrained over 1.2K paired tissue slides each of which includes a haematoxylin and eosin (H&E)-stained whole-slide image and its corresponding spatial transcriptomic profile. From these tissue slides, we derive 17 million image-expression pairs and a unified gene panel that contains over 20K protein-coding genes for pretraining. At inference time, the model can be applied to cross-modality generation (e.g., predict gene expression at cellular resolutions from histology images), predictive tasks at cell / region / slide levels, as well as analysis of intercellular communication and cell subtype identification.

Model Overview

image

The model is pretrained with a large corpus of spatial data ranging from diverse organs, species and health/disease states and can generalize to unseen tissues, organs, and species for prediction at cell, region and slide levels as well as informing spatial analysis and discovery.

image

Datasets

All datasets used for the training and evaluation of our model are publicly available. The HEST-1K can be accessed HuggingFace. The Xenium human breast tissue slides were included in HEST-1K. We used the data version released by the original paper in 10XGenomics. The dataset of human lung tissues with pulmonary fibrosis is deposited in the GEO database under accession number GSE250346.

Reproducing the Results

Please follow the steps below to reproduce the results and analysis performed in this study.

  1. Prerequisite

First of all, Anaconda or Miniconda is needed to run the commands in this guide. You can check if it is installed via running

 conda

If it is not installed, then run the following commands:

 wget https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Linux-x86_64.sh
chmod +x Anaconda3-2023.03-1-Linux-x86_64.sh
./Anaconda3-2023.03-1-Linux-x86_64.sh
vim ~/.bashrc
export PATH=/root/anaconda3/bin:$PATHsource~/.bashrc

Then clone this repository by running the following command in a new terminal:

 git clone https://github.com/uhlerlab/TissueFormer

Make sure you are in the root directory (i.e., TissueFormer/) by typing

cd TissueFormer

Create a new environment with the packages provided by environment.yml:

 conda env create -f environment.yml -n tissueformer
conda activate tissueformer
  1. Data preprocessing

We provide the instruction for using our data preprocessing pipeline.

  1. Training (pretraining and finetuning)

TissueFormer adopts two-stage curriculum learning for pretraining: the model was first trained with spot-resolution data (e.g., Visium slides) and further trained with cell-resolution data (e.g., Xenium slides). For applications, the pretrained TissueFormer can be directly applied to zero-shot predictions on new datasets or finetuned with new data. We provide the instruction for using our pipeline of pretraining and finetuning.

  1. Inference for prediction

After pretraining, TissueFormer is capable of handling various predictive tasks only using histology images of test samples. One typical task is cross-modality generation, i.e., predicting spatial gene expression from histology images. Furthermore, the pretrained model can be applied to predictions at different biological scales (cell-level, region-level, slide-level) from histology images. We provide the instruction for applying TissueFormer to predictions.

  1. Inference for analysis

Apart from predictive tasks, TissueFormer supports analysis of intercellular communication and cell subtying from histology images. For these, the pretrained model provides whole-slide cell-cell attention maps and cell-level embeddings for interpreting and analyzing the mechanism. We provide the instruction for applying TissueFormer to analysis.

  1. Visualization

All illustrative figures (Fig. 1 and Supplementary Fig. 1-2) in this study were made using Draw.io, PowerPoint and Adobe Illustrator.

Pointers for nonillustrative figures:

  • ./analysis/gene_exp_pred_visium.ipynb: Fig. 2, Supplementary Fig. 3-4
  • ./analysis/gene_exp_pred_xenium.ipynb: Fig. 3, Supplementary Fig. 5-7
  • ./analysis/diagnosis_pred_lung.ipynb: Fig. 4, Supplementary Fig. 8
  • ./analysis/analysis_lung_fibrosis.ipynb: Fig. 5, Supplementary Fig. 9-10
  • ./analysis/analysis_breast_tumor.ipynb: Supplementary Fig. 11

Apply TissueFormer to User-provided Datasets

Applying TissueFormer to any new dataset typically involves the following steps:

  1. Load preprocessed dataset
  2. Load pretrained model checkpoints
  3. Optional: finetune the model on new datasets
  4. Apply the model for prediction (e.g., predict gene expression from histology images)
  5. Apply the model for analysis (extract the cell embeddings and attention maps)

Application Demo 1

Here we use the test Xenium samples (TENX126, TENX123, TENX124, TENX121, TENX119, TENX118) as an example to demonstrate how to use our model on test data and reproduce the results.

  1. Load preprocessed dataset

One can download the preprocessed data from this Google Drive into a folder ./data

  1. Load pretrained model checkpoints

The same google drive repository contains the pretrained model checkpoints and one can download them into a folder ./checkpoint.

  1. Apply the model for prediction

Then one can refer to ./prediction/main_evaluate_xenium.py and modify the directory paths storing the dataset, model checkpoint and results:

dir_path='./data/hest_data_xenium_protein_preprocess'pretrain_model_path='./checkpoint/ours_pretrain_xenium_sample+_small.pth'result_path=f'./result/gene_expression_prediction/{test_sample}'

After modifying the paths, one can run the following script to execute prediction on these test samples (the batch_size can be adjusted to balance the memory and time costs):

 python main_evaluate_xenium.py --domain_protocol sample --hvg_gene_tops 400 --method ours --gene_emb_dim 128 \
--enc1_hidden_channels 128 --enc2_hidden_channels 128 --enc1_num_layers_prop 2 --enc1_num_layers_mlp 2 --enc2_num_layers_mlp 1 \
--neighbor_num 1000 --batch_size 1000 --device 7

The prediction results are stored into the path ./result/gene_expression_prediction/.

  1. Visualization

The visualization code for our results (Fig. 3a, Supplementary Fig. 5) is provided in this demo1.

image

Application Demo 2

For applying TissueFormer to user-provided datasets, we provide a demo2 as an example. One can use this demo by replacing the dataset with one's own and following the instruction below.

First, one needs to specify the directory path storing the dataset and load the dataset that is split for training and test:

dir_path='/ewsc/wuqitian/lung_preprocess'meta_info=pd.read_csv("../../data/meta_info_lung.csv")
# train data can be used as the reference for in-context learning or for finetuning the modeltrain_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[:-1]
# test data for evaluationtest_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[-1:]
# create dataloadertrain_datasets=dataset_create(dir_path, train_samples)
train_dataloader=DataLoader(train_datasets, batch_size=1, shuffle=True)
test_datasets=dataset_create(dir_path, test_samples)
test_dataloader=DataLoader(test_datasets, batch_size=1, shuffle=False)

Second, load the pretrained model checkpoint (one can choose the pretrained model version):

pretrained_state_dict=torch.load('../../model_checkpoints/ours_pretrain_xenium_lung.pth') # one can choose the model versionencoder1_pretrained_dict= {k: vfork, vinpretrained_state_dict.items() ifk.startswith("encoder1.")}
model_state_dict=model_ours.state_dict()
encoder1_model_dict= {k: vfork, vinmodel_state_dict.items() ifk.startswith("encoder1.")}
fork, vinencoder1_pretrained_dict.items():
assert (kinencoder1_model_dict)
assert (v.size() ==encoder1_model_dict[k].size())
model_state_dict.update(encoder1_pretrained_dict)
model_ours.load_state_dict(model_state_dict)

Later on, one can use the model for prediction, analysis (extract cell-level embeddings and attentions) or finetuning the model with downstream labels by following the scripts in demo2.

About

No description, website, or topics provided.

Resources

Stars

8 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

TissueFormer: A Multi-Modal Foundation Model for Spatial Biology

TissueFormer is pretrained over 1.2K paired tissue slides each of which includes a haematoxylin and eosin (H&E)-stained whole-slide image and its corresponding spatial transcriptomic profile. From these tissue slides, we derive 17 million image-expression pairs and a unified gene panel that contains over 20K protein-coding genes for pretraining. At inference time, the model can be applied to cross-modality generation (e.g., predict gene expression at cellular resolutions from histology images), predictive tasks at cell / region / slide levels, as well as analysis of intercellular communication and cell subtype identification.

Model Overview

image

The model is pretrained with a large corpus of spatial data ranging from diverse organs, species and health/disease states and can generalize to unseen tissues, organs, and species for prediction at cell, region and slide levels as well as informing spatial analysis and discovery.

image

Datasets

All datasets used for the training and evaluation of our model are publicly available. The HEST-1K can be accessed HuggingFace. The Xenium human breast tissue slides were included in HEST-1K. We used the data version released by the original paper in 10XGenomics. The dataset of human lung tissues with pulmonary fibrosis is deposited in the GEO database under accession number GSE250346.

Reproducing the Results

Please follow the steps below to reproduce the results and analysis performed in this study.

  1. Prerequisite

First of all, Anaconda or Miniconda is needed to run the commands in this guide. You can check if it is installed via running

 conda

If it is not installed, then run the following commands:

 wget https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Linux-x86_64.sh
chmod +x Anaconda3-2023.03-1-Linux-x86_64.sh
./Anaconda3-2023.03-1-Linux-x86_64.sh
vim ~/.bashrc
export PATH=/root/anaconda3/bin:$PATHsource~/.bashrc

Then clone this repository by running the following command in a new terminal:

 git clone https://github.com/uhlerlab/TissueFormer

Make sure you are in the root directory (i.e., TissueFormer/) by typing

cd TissueFormer

Create a new environment with the packages provided by environment.yml:

 conda env create -f environment.yml -n tissueformer
conda activate tissueformer
  1. Data preprocessing

We provide the instruction for using our data preprocessing pipeline.

  1. Training (pretraining and finetuning)

TissueFormer adopts two-stage curriculum learning for pretraining: the model was first trained with spot-resolution data (e.g., Visium slides) and further trained with cell-resolution data (e.g., Xenium slides). For applications, the pretrained TissueFormer can be directly applied to zero-shot predictions on new datasets or finetuned with new data. We provide the instruction for using our pipeline of pretraining and finetuning.

  1. Inference for prediction

After pretraining, TissueFormer is capable of handling various predictive tasks only using histology images of test samples. One typical task is cross-modality generation, i.e., predicting spatial gene expression from histology images. Furthermore, the pretrained model can be applied to predictions at different biological scales (cell-level, region-level, slide-level) from histology images. We provide the instruction for applying TissueFormer to predictions.

  1. Inference for analysis

Apart from predictive tasks, TissueFormer supports analysis of intercellular communication and cell subtying from histology images. For these, the pretrained model provides whole-slide cell-cell attention maps and cell-level embeddings for interpreting and analyzing the mechanism. We provide the instruction for applying TissueFormer to analysis.

  1. Visualization

All illustrative figures (Fig. 1 and Supplementary Fig. 1-2) in this study were made using Draw.io, PowerPoint and Adobe Illustrator.

Pointers for nonillustrative figures:

  • ./analysis/gene_exp_pred_visium.ipynb: Fig. 2, Supplementary Fig. 3-4
  • ./analysis/gene_exp_pred_xenium.ipynb: Fig. 3, Supplementary Fig. 5-7
  • ./analysis/diagnosis_pred_lung.ipynb: Fig. 4, Supplementary Fig. 8
  • ./analysis/analysis_lung_fibrosis.ipynb: Fig. 5, Supplementary Fig. 9-10
  • ./analysis/analysis_breast_tumor.ipynb: Supplementary Fig. 11

Apply TissueFormer to User-provided Datasets

Applying TissueFormer to any new dataset typically involves the following steps:

  1. Load preprocessed dataset
  2. Load pretrained model checkpoints
  3. Optional: finetune the model on new datasets
  4. Apply the model for prediction (e.g., predict gene expression from histology images)
  5. Apply the model for analysis (extract the cell embeddings and attention maps)

Application Demo 1

Here we use the test Xenium samples (TENX126, TENX123, TENX124, TENX121, TENX119, TENX118) as an example to demonstrate how to use our model on test data and reproduce the results.

  1. Load preprocessed dataset

One can download the preprocessed data from this Google Drive into a folder ./data

  1. Load pretrained model checkpoints

The same google drive repository contains the pretrained model checkpoints and one can download them into a folder ./checkpoint.

  1. Apply the model for prediction

Then one can refer to ./prediction/main_evaluate_xenium.py and modify the directory paths storing the dataset, model checkpoint and results:

dir_path='./data/hest_data_xenium_protein_preprocess'pretrain_model_path='./checkpoint/ours_pretrain_xenium_sample+_small.pth'result_path=f'./result/gene_expression_prediction/{test_sample}'

After modifying the paths, one can run the following script to execute prediction on these test samples (the batch_size can be adjusted to balance the memory and time costs):

 python main_evaluate_xenium.py --domain_protocol sample --hvg_gene_tops 400 --method ours --gene_emb_dim 128 \
--enc1_hidden_channels 128 --enc2_hidden_channels 128 --enc1_num_layers_prop 2 --enc1_num_layers_mlp 2 --enc2_num_layers_mlp 1 \
--neighbor_num 1000 --batch_size 1000 --device 7

The prediction results are stored into the path ./result/gene_expression_prediction/.

  1. Visualization

The visualization code for our results (Fig. 3a, Supplementary Fig. 5) is provided in this demo1.

image

Application Demo 2

For applying TissueFormer to user-provided datasets, we provide a demo2 as an example. One can use this demo by replacing the dataset with one's own and following the instruction below.

First, one needs to specify the directory path storing the dataset and load the dataset that is split for training and test:

dir_path='/ewsc/wuqitian/lung_preprocess'meta_info=pd.read_csv("../../data/meta_info_lung.csv")
# train data can be used as the reference for in-context learning or for finetuning the modeltrain_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[:-1]
# test data for evaluationtest_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[-1:]
# create dataloadertrain_datasets=dataset_create(dir_path, train_samples)
train_dataloader=DataLoader(train_datasets, batch_size=1, shuffle=True)
test_datasets=dataset_create(dir_path, test_samples)
test_dataloader=DataLoader(test_datasets, batch_size=1, shuffle=False)

Second, load the pretrained model checkpoint (one can choose the pretrained model version):

pretrained_state_dict=torch.load('../../model_checkpoints/ours_pretrain_xenium_lung.pth') # one can choose the model versionencoder1_pretrained_dict= {k: vfork, vinpretrained_state_dict.items() ifk.startswith("encoder1.")}
model_state_dict=model_ours.state_dict()
encoder1_model_dict= {k: vfork, vinmodel_state_dict.items() ifk.startswith("encoder1.")}
fork, vinencoder1_pretrained_dict.items():
assert (kinencoder1_model_dict)
assert (v.size() ==encoder1_model_dict[k].size())
model_state_dict.update(encoder1_pretrained_dict)
model_ours.load_state_dict(model_state_dict)

Later on, one can use the model for prediction, analysis (extract cell-level embeddings and attentions) or finetuning the model with downstream labels by following the scripts in demo2.

About

No description, website, or topics provided.

Resources

Stars

8 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

TissueFormer: A Multi-Modal Foundation Model for Spatial Biology

TissueFormer is pretrained over 1.2K paired tissue slides each of which includes a haematoxylin and eosin (H&E)-stained whole-slide image and its corresponding spatial transcriptomic profile. From these tissue slides, we derive 17 million image-expression pairs and a unified gene panel that contains over 20K protein-coding genes for pretraining. At inference time, the model can be applied to cross-modality generation (e.g., predict gene expression at cellular resolutions from histology images), predictive tasks at cell / region / slide levels, as well as analysis of intercellular communication and cell subtype identification.

Model Overview

image

The model is pretrained with a large corpus of spatial data ranging from diverse organs, species and health/disease states and can generalize to unseen tissues, organs, and species for prediction at cell, region and slide levels as well as informing spatial analysis and discovery.

image

Datasets

All datasets used for the training and evaluation of our model are publicly available. The HEST-1K can be accessed HuggingFace. The Xenium human breast tissue slides were included in HEST-1K. We used the data version released by the original paper in 10XGenomics. The dataset of human lung tissues with pulmonary fibrosis is deposited in the GEO database under accession number GSE250346.

Reproducing the Results

Please follow the steps below to reproduce the results and analysis performed in this study.

  1. Prerequisite

First of all, Anaconda or Miniconda is needed to run the commands in this guide. You can check if it is installed via running

 conda

If it is not installed, then run the following commands:

 wget https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Linux-x86_64.sh
chmod +x Anaconda3-2023.03-1-Linux-x86_64.sh
./Anaconda3-2023.03-1-Linux-x86_64.sh
vim ~/.bashrc
export PATH=/root/anaconda3/bin:$PATHsource~/.bashrc

Then clone this repository by running the following command in a new terminal:

 git clone https://github.com/uhlerlab/TissueFormer

Make sure you are in the root directory (i.e., TissueFormer/) by typing

cd TissueFormer

Create a new environment with the packages provided by environment.yml:

 conda env create -f environment.yml -n tissueformer
conda activate tissueformer
  1. Data preprocessing

We provide the instruction for using our data preprocessing pipeline.

  1. Training (pretraining and finetuning)

TissueFormer adopts two-stage curriculum learning for pretraining: the model was first trained with spot-resolution data (e.g., Visium slides) and further trained with cell-resolution data (e.g., Xenium slides). For applications, the pretrained TissueFormer can be directly applied to zero-shot predictions on new datasets or finetuned with new data. We provide the instruction for using our pipeline of pretraining and finetuning.

  1. Inference for prediction

After pretraining, TissueFormer is capable of handling various predictive tasks only using histology images of test samples. One typical task is cross-modality generation, i.e., predicting spatial gene expression from histology images. Furthermore, the pretrained model can be applied to predictions at different biological scales (cell-level, region-level, slide-level) from histology images. We provide the instruction for applying TissueFormer to predictions.

  1. Inference for analysis

Apart from predictive tasks, TissueFormer supports analysis of intercellular communication and cell subtying from histology images. For these, the pretrained model provides whole-slide cell-cell attention maps and cell-level embeddings for interpreting and analyzing the mechanism. We provide the instruction for applying TissueFormer to analysis.

  1. Visualization

All illustrative figures (Fig. 1 and Supplementary Fig. 1-2) in this study were made using Draw.io, PowerPoint and Adobe Illustrator.

Pointers for nonillustrative figures:

  • ./analysis/gene_exp_pred_visium.ipynb: Fig. 2, Supplementary Fig. 3-4
  • ./analysis/gene_exp_pred_xenium.ipynb: Fig. 3, Supplementary Fig. 5-7
  • ./analysis/diagnosis_pred_lung.ipynb: Fig. 4, Supplementary Fig. 8
  • ./analysis/analysis_lung_fibrosis.ipynb: Fig. 5, Supplementary Fig. 9-10
  • ./analysis/analysis_breast_tumor.ipynb: Supplementary Fig. 11

Apply TissueFormer to User-provided Datasets

Applying TissueFormer to any new dataset typically involves the following steps:

  1. Load preprocessed dataset
  2. Load pretrained model checkpoints
  3. Optional: finetune the model on new datasets
  4. Apply the model for prediction (e.g., predict gene expression from histology images)
  5. Apply the model for analysis (extract the cell embeddings and attention maps)

Application Demo 1

Here we use the test Xenium samples (TENX126, TENX123, TENX124, TENX121, TENX119, TENX118) as an example to demonstrate how to use our model on test data and reproduce the results.

  1. Load preprocessed dataset

One can download the preprocessed data from this Google Drive into a folder ./data

  1. Load pretrained model checkpoints

The same google drive repository contains the pretrained model checkpoints and one can download them into a folder ./checkpoint.

  1. Apply the model for prediction

Then one can refer to ./prediction/main_evaluate_xenium.py and modify the directory paths storing the dataset, model checkpoint and results:

dir_path='./data/hest_data_xenium_protein_preprocess'pretrain_model_path='./checkpoint/ours_pretrain_xenium_sample+_small.pth'result_path=f'./result/gene_expression_prediction/{test_sample}'

After modifying the paths, one can run the following script to execute prediction on these test samples (the batch_size can be adjusted to balance the memory and time costs):

 python main_evaluate_xenium.py --domain_protocol sample --hvg_gene_tops 400 --method ours --gene_emb_dim 128 \
--enc1_hidden_channels 128 --enc2_hidden_channels 128 --enc1_num_layers_prop 2 --enc1_num_layers_mlp 2 --enc2_num_layers_mlp 1 \
--neighbor_num 1000 --batch_size 1000 --device 7

The prediction results are stored into the path ./result/gene_expression_prediction/.

  1. Visualization

The visualization code for our results (Fig. 3a, Supplementary Fig. 5) is provided in this demo1.

image

Application Demo 2

For applying TissueFormer to user-provided datasets, we provide a demo2 as an example. One can use this demo by replacing the dataset with one's own and following the instruction below.

First, one needs to specify the directory path storing the dataset and load the dataset that is split for training and test:

dir_path='/ewsc/wuqitian/lung_preprocess'meta_info=pd.read_csv("../../data/meta_info_lung.csv")
# train data can be used as the reference for in-context learning or for finetuning the modeltrain_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[:-1]
# test data for evaluationtest_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[-1:]
# create dataloadertrain_datasets=dataset_create(dir_path, train_samples)
train_dataloader=DataLoader(train_datasets, batch_size=1, shuffle=True)
test_datasets=dataset_create(dir_path, test_samples)
test_dataloader=DataLoader(test_datasets, batch_size=1, shuffle=False)

Second, load the pretrained model checkpoint (one can choose the pretrained model version):

pretrained_state_dict=torch.load('../../model_checkpoints/ours_pretrain_xenium_lung.pth') # one can choose the model versionencoder1_pretrained_dict= {k: vfork, vinpretrained_state_dict.items() ifk.startswith("encoder1.")}
model_state_dict=model_ours.state_dict()
encoder1_model_dict= {k: vfork, vinmodel_state_dict.items() ifk.startswith("encoder1.")}
fork, vinencoder1_pretrained_dict.items():
assert (kinencoder1_model_dict)
assert (v.size() ==encoder1_model_dict[k].size())
model_state_dict.update(encoder1_pretrained_dict)
model_ours.load_state_dict(model_state_dict)

Later on, one can use the model for prediction, analysis (extract cell-level embeddings and attentions) or finetuning the model with downstream labels by following the scripts in demo2.

About

No description, website, or topics provided.

Resources

Stars

8 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

TissueFormer: A Multi-Modal Foundation Model for Spatial Biology

TissueFormer is pretrained over 1.2K paired tissue slides each of which includes a haematoxylin and eosin (H&E)-stained whole-slide image and its corresponding spatial transcriptomic profile. From these tissue slides, we derive 17 million image-expression pairs and a unified gene panel that contains over 20K protein-coding genes for pretraining. At inference time, the model can be applied to cross-modality generation (e.g., predict gene expression at cellular resolutions from histology images), predictive tasks at cell / region / slide levels, as well as analysis of intercellular communication and cell subtype identification.

Model Overview

image

The model is pretrained with a large corpus of spatial data ranging from diverse organs, species and health/disease states and can generalize to unseen tissues, organs, and species for prediction at cell, region and slide levels as well as informing spatial analysis and discovery.

image

Datasets

All datasets used for the training and evaluation of our model are publicly available. The HEST-1K can be accessed HuggingFace. The Xenium human breast tissue slides were included in HEST-1K. We used the data version released by the original paper in 10XGenomics. The dataset of human lung tissues with pulmonary fibrosis is deposited in the GEO database under accession number GSE250346.

Reproducing the Results

Please follow the steps below to reproduce the results and analysis performed in this study.

  1. Prerequisite

First of all, Anaconda or Miniconda is needed to run the commands in this guide. You can check if it is installed via running

 conda

If it is not installed, then run the following commands:

 wget https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Linux-x86_64.sh
chmod +x Anaconda3-2023.03-1-Linux-x86_64.sh
./Anaconda3-2023.03-1-Linux-x86_64.sh
vim ~/.bashrc
export PATH=/root/anaconda3/bin:$PATHsource~/.bashrc

Then clone this repository by running the following command in a new terminal:

 git clone https://github.com/uhlerlab/TissueFormer

Make sure you are in the root directory (i.e., TissueFormer/) by typing

cd TissueFormer

Create a new environment with the packages provided by environment.yml:

 conda env create -f environment.yml -n tissueformer
conda activate tissueformer
  1. Data preprocessing

We provide the instruction for using our data preprocessing pipeline.

  1. Training (pretraining and finetuning)

TissueFormer adopts two-stage curriculum learning for pretraining: the model was first trained with spot-resolution data (e.g., Visium slides) and further trained with cell-resolution data (e.g., Xenium slides). For applications, the pretrained TissueFormer can be directly applied to zero-shot predictions on new datasets or finetuned with new data. We provide the instruction for using our pipeline of pretraining and finetuning.

  1. Inference for prediction

After pretraining, TissueFormer is capable of handling various predictive tasks only using histology images of test samples. One typical task is cross-modality generation, i.e., predicting spatial gene expression from histology images. Furthermore, the pretrained model can be applied to predictions at different biological scales (cell-level, region-level, slide-level) from histology images. We provide the instruction for applying TissueFormer to predictions.

  1. Inference for analysis

Apart from predictive tasks, TissueFormer supports analysis of intercellular communication and cell subtying from histology images. For these, the pretrained model provides whole-slide cell-cell attention maps and cell-level embeddings for interpreting and analyzing the mechanism. We provide the instruction for applying TissueFormer to analysis.

  1. Visualization

All illustrative figures (Fig. 1 and Supplementary Fig. 1-2) in this study were made using Draw.io, PowerPoint and Adobe Illustrator.

Pointers for nonillustrative figures:

  • ./analysis/gene_exp_pred_visium.ipynb: Fig. 2, Supplementary Fig. 3-4
  • ./analysis/gene_exp_pred_xenium.ipynb: Fig. 3, Supplementary Fig. 5-7
  • ./analysis/diagnosis_pred_lung.ipynb: Fig. 4, Supplementary Fig. 8
  • ./analysis/analysis_lung_fibrosis.ipynb: Fig. 5, Supplementary Fig. 9-10
  • ./analysis/analysis_breast_tumor.ipynb: Supplementary Fig. 11

Apply TissueFormer to User-provided Datasets

Applying TissueFormer to any new dataset typically involves the following steps:

  1. Load preprocessed dataset
  2. Load pretrained model checkpoints
  3. Optional: finetune the model on new datasets
  4. Apply the model for prediction (e.g., predict gene expression from histology images)
  5. Apply the model for analysis (extract the cell embeddings and attention maps)

Application Demo 1

Here we use the test Xenium samples (TENX126, TENX123, TENX124, TENX121, TENX119, TENX118) as an example to demonstrate how to use our model on test data and reproduce the results.

  1. Load preprocessed dataset

One can download the preprocessed data from this Google Drive into a folder ./data

  1. Load pretrained model checkpoints

The same google drive repository contains the pretrained model checkpoints and one can download them into a folder ./checkpoint.

  1. Apply the model for prediction

Then one can refer to ./prediction/main_evaluate_xenium.py and modify the directory paths storing the dataset, model checkpoint and results:

dir_path='./data/hest_data_xenium_protein_preprocess'pretrain_model_path='./checkpoint/ours_pretrain_xenium_sample+_small.pth'result_path=f'./result/gene_expression_prediction/{test_sample}'

After modifying the paths, one can run the following script to execute prediction on these test samples (the batch_size can be adjusted to balance the memory and time costs):

 python main_evaluate_xenium.py --domain_protocol sample --hvg_gene_tops 400 --method ours --gene_emb_dim 128 \
--enc1_hidden_channels 128 --enc2_hidden_channels 128 --enc1_num_layers_prop 2 --enc1_num_layers_mlp 2 --enc2_num_layers_mlp 1 \
--neighbor_num 1000 --batch_size 1000 --device 7

The prediction results are stored into the path ./result/gene_expression_prediction/.

  1. Visualization

The visualization code for our results (Fig. 3a, Supplementary Fig. 5) is provided in this demo1.

image

Application Demo 2

For applying TissueFormer to user-provided datasets, we provide a demo2 as an example. One can use this demo by replacing the dataset with one's own and following the instruction below.

First, one needs to specify the directory path storing the dataset and load the dataset that is split for training and test:

dir_path='/ewsc/wuqitian/lung_preprocess'meta_info=pd.read_csv("../../data/meta_info_lung.csv")
# train data can be used as the reference for in-context learning or for finetuning the modeltrain_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[:-1]
# test data for evaluationtest_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[-1:]
# create dataloadertrain_datasets=dataset_create(dir_path, train_samples)
train_dataloader=DataLoader(train_datasets, batch_size=1, shuffle=True)
test_datasets=dataset_create(dir_path, test_samples)
test_dataloader=DataLoader(test_datasets, batch_size=1, shuffle=False)

Second, load the pretrained model checkpoint (one can choose the pretrained model version):

pretrained_state_dict=torch.load('../../model_checkpoints/ours_pretrain_xenium_lung.pth') # one can choose the model versionencoder1_pretrained_dict= {k: vfork, vinpretrained_state_dict.items() ifk.startswith("encoder1.")}
model_state_dict=model_ours.state_dict()
encoder1_model_dict= {k: vfork, vinmodel_state_dict.items() ifk.startswith("encoder1.")}
fork, vinencoder1_pretrained_dict.items():
assert (kinencoder1_model_dict)
assert (v.size() ==encoder1_model_dict[k].size())
model_state_dict.update(encoder1_pretrained_dict)
model_ours.load_state_dict(model_state_dict)

Later on, one can use the model for prediction, analysis (extract cell-level embeddings and attentions) or finetuning the model with downstream labels by following the scripts in demo2.

About

No description, website, or topics provided.

Resources

Stars

8 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

TissueFormer: A Multi-Modal Foundation Model for Spatial Biology

TissueFormer is pretrained over 1.2K paired tissue slides each of which includes a haematoxylin and eosin (H&E)-stained whole-slide image and its corresponding spatial transcriptomic profile. From these tissue slides, we derive 17 million image-expression pairs and a unified gene panel that contains over 20K protein-coding genes for pretraining. At inference time, the model can be applied to cross-modality generation (e.g., predict gene expression at cellular resolutions from histology images), predictive tasks at cell / region / slide levels, as well as analysis of intercellular communication and cell subtype identification.

Model Overview

image

The model is pretrained with a large corpus of spatial data ranging from diverse organs, species and health/disease states and can generalize to unseen tissues, organs, and species for prediction at cell, region and slide levels as well as informing spatial analysis and discovery.

image

Datasets

All datasets used for the training and evaluation of our model are publicly available. The HEST-1K can be accessed HuggingFace. The Xenium human breast tissue slides were included in HEST-1K. We used the data version released by the original paper in 10XGenomics. The dataset of human lung tissues with pulmonary fibrosis is deposited in the GEO database under accession number GSE250346.

Reproducing the Results

Please follow the steps below to reproduce the results and analysis performed in this study.

  1. Prerequisite

First of all, Anaconda or Miniconda is needed to run the commands in this guide. You can check if it is installed via running

 conda

If it is not installed, then run the following commands:

 wget https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Linux-x86_64.sh
chmod +x Anaconda3-2023.03-1-Linux-x86_64.sh
./Anaconda3-2023.03-1-Linux-x86_64.sh
vim ~/.bashrc
export PATH=/root/anaconda3/bin:$PATHsource~/.bashrc

Then clone this repository by running the following command in a new terminal:

 git clone https://github.com/uhlerlab/TissueFormer

Make sure you are in the root directory (i.e., TissueFormer/) by typing

cd TissueFormer

Create a new environment with the packages provided by environment.yml:

 conda env create -f environment.yml -n tissueformer
conda activate tissueformer
  1. Data preprocessing

We provide the instruction for using our data preprocessing pipeline.

  1. Training (pretraining and finetuning)

TissueFormer adopts two-stage curriculum learning for pretraining: the model was first trained with spot-resolution data (e.g., Visium slides) and further trained with cell-resolution data (e.g., Xenium slides). For applications, the pretrained TissueFormer can be directly applied to zero-shot predictions on new datasets or finetuned with new data. We provide the instruction for using our pipeline of pretraining and finetuning.

  1. Inference for prediction

After pretraining, TissueFormer is capable of handling various predictive tasks only using histology images of test samples. One typical task is cross-modality generation, i.e., predicting spatial gene expression from histology images. Furthermore, the pretrained model can be applied to predictions at different biological scales (cell-level, region-level, slide-level) from histology images. We provide the instruction for applying TissueFormer to predictions.

  1. Inference for analysis

Apart from predictive tasks, TissueFormer supports analysis of intercellular communication and cell subtying from histology images. For these, the pretrained model provides whole-slide cell-cell attention maps and cell-level embeddings for interpreting and analyzing the mechanism. We provide the instruction for applying TissueFormer to analysis.

  1. Visualization

All illustrative figures (Fig. 1 and Supplementary Fig. 1-2) in this study were made using Draw.io, PowerPoint and Adobe Illustrator.

Pointers for nonillustrative figures:

  • ./analysis/gene_exp_pred_visium.ipynb: Fig. 2, Supplementary Fig. 3-4
  • ./analysis/gene_exp_pred_xenium.ipynb: Fig. 3, Supplementary Fig. 5-7
  • ./analysis/diagnosis_pred_lung.ipynb: Fig. 4, Supplementary Fig. 8
  • ./analysis/analysis_lung_fibrosis.ipynb: Fig. 5, Supplementary Fig. 9-10
  • ./analysis/analysis_breast_tumor.ipynb: Supplementary Fig. 11

Apply TissueFormer to User-provided Datasets

Applying TissueFormer to any new dataset typically involves the following steps:

  1. Load preprocessed dataset
  2. Load pretrained model checkpoints
  3. Optional: finetune the model on new datasets
  4. Apply the model for prediction (e.g., predict gene expression from histology images)
  5. Apply the model for analysis (extract the cell embeddings and attention maps)

Application Demo 1

Here we use the test Xenium samples (TENX126, TENX123, TENX124, TENX121, TENX119, TENX118) as an example to demonstrate how to use our model on test data and reproduce the results.

  1. Load preprocessed dataset

One can download the preprocessed data from this Google Drive into a folder ./data

  1. Load pretrained model checkpoints

The same google drive repository contains the pretrained model checkpoints and one can download them into a folder ./checkpoint.

  1. Apply the model for prediction

Then one can refer to ./prediction/main_evaluate_xenium.py and modify the directory paths storing the dataset, model checkpoint and results:

dir_path='./data/hest_data_xenium_protein_preprocess'pretrain_model_path='./checkpoint/ours_pretrain_xenium_sample+_small.pth'result_path=f'./result/gene_expression_prediction/{test_sample}'

After modifying the paths, one can run the following script to execute prediction on these test samples (the batch_size can be adjusted to balance the memory and time costs):

 python main_evaluate_xenium.py --domain_protocol sample --hvg_gene_tops 400 --method ours --gene_emb_dim 128 \
--enc1_hidden_channels 128 --enc2_hidden_channels 128 --enc1_num_layers_prop 2 --enc1_num_layers_mlp 2 --enc2_num_layers_mlp 1 \
--neighbor_num 1000 --batch_size 1000 --device 7

The prediction results are stored into the path ./result/gene_expression_prediction/.

  1. Visualization

The visualization code for our results (Fig. 3a, Supplementary Fig. 5) is provided in this demo1.

image

Application Demo 2

For applying TissueFormer to user-provided datasets, we provide a demo2 as an example. One can use this demo by replacing the dataset with one's own and following the instruction below.

First, one needs to specify the directory path storing the dataset and load the dataset that is split for training and test:

dir_path='/ewsc/wuqitian/lung_preprocess'meta_info=pd.read_csv("../../data/meta_info_lung.csv")
# train data can be used as the reference for in-context learning or for finetuning the modeltrain_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[:-1]
# test data for evaluationtest_samples=meta_info[meta_info['affect'] =='Unaffected']['sample'].tolist()[-1:]
# create dataloadertrain_datasets=dataset_create(dir_path, train_samples)
train_dataloader=DataLoader(train_datasets, batch_size=1, shuffle=True)
test_datasets=dataset_create(dir_path, test_samples)
test_dataloader=DataLoader(test_datasets, batch_size=1, shuffle=False)

Second, load the pretrained model checkpoint (one can choose the pretrained model version):

pretrained_state_dict=torch.load('../../model_checkpoints/ours_pretrain_xenium_lung.pth') # one can choose the model versionencoder1_pretrained_dict= {k: vfork, vinpretrained_state_dict.items() ifk.startswith("encoder1.")}
model_state_dict=model_ours.state_dict()
encoder1_model_dict= {k: vfork, vinmodel_state_dict.items() ifk.startswith("encoder1.")}
fork, vinencoder1_pretrained_dict.items():
assert (kinencoder1_model_dict)
assert (v.size() ==encoder1_model_dict[k].size())
model_state_dict.update(encoder1_pretrained_dict)
model_ours.load_state_dict(model_state_dict)

Later on, one can use the model for prediction, analysis (extract cell-level embeddings and attentions) or finetuning the model with downstream labels by following the scripts in demo2.

About

No description, website, or topics provided.

Resources

Stars

8 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages