ctheodoris commited on
Commit
dc90822
1 Parent(s): abafc19

update mtl cell classification notebook format

Browse files
examples/mtl_cell_classification.ipynb ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "866f100c-e11a-4e7b-a37c-831775d845a7",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Geneformer Multi-Task Cell Classifier Tutorial\n",
9
+ "\n",
10
+ "This tutorial demonstrates how to use the Geneformer Multi-Task Cell Classifier and optimizatize hyperparameter for fine-tuning"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "id": "311ba456-b44d-40c7-941d-3fc03bcda85a",
16
+ "metadata": {},
17
+ "source": [
18
+ "## 1. Installation and Imports\n",
19
+ "\n",
20
+ "First import the necessary modules."
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": 3,
26
+ "id": "cd9defdc-0524-4c3b-a741-27117ed3a5be",
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "from geneformer import MTLClassifier"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "markdown",
35
+ "id": "790e9c3c-f6d9-44b3-b9a5-05725760f4fd",
36
+ "metadata": {},
37
+ "source": [
38
+ "## 2. Set up Paths and Parameters\n",
39
+ "\n",
40
+ "Now, let's set up the necessary paths and parameters for our classifier. We'll also define our task columns, which are specific columns from our dataset that represent the classification tasks we want to train the model on."
41
+ ]
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "execution_count": null,
46
+ "id": "04a04197-8e45-47f8-a86f-202209ea10ae",
47
+ "metadata": {},
48
+ "outputs": [],
49
+ "source": [
50
+ "# Define paths\n",
51
+ "pretrained_path = \"/path/to/pretrained/Geneformer/model\" \n",
52
+ "# input data is tokenized rank value encodings generated by Geneformer tokenizer (see tokenizing_scRNAseq_data.ipynb)\n",
53
+ "train_path = \"/path/to/train/data.dataset\"\n",
54
+ "val_path = \"/path/to/val/data.dataset\"\n",
55
+ "test_path = \"/path/to/test/data.dataset\"\n",
56
+ "results_dir = \"/path/to/results/directory\"\n",
57
+ "model_save_path = \"/path/to/model/save/path\"\n",
58
+ "tensorboard_log_dir = \"/path/to/tensorboard/log/dir\"\n",
59
+ "\n",
60
+ "# Define tasks and hyperparameters\n",
61
+ "# task_columns should be a list of column names from your dataset\n",
62
+ "# Each column represents a specific classification task (e.g. cell type, disease state)\n",
63
+ "task_columns = [\"cell_type\", \"disease_state\"] # Example task columns\n",
64
+ "\n",
65
+ "hyperparameters = {\n",
66
+ " \"learning_rate\": {\"type\": \"float\", \"low\": 1e-5, \"high\": 1e-3, \"log\": True},\n",
67
+ " \"warmup_ratio\": {\"type\": \"float\", \"low\": 0.005, \"high\": 0.01},\n",
68
+ " \"weight_decay\": {\"type\": \"float\", \"low\": 0.01, \"high\": 0.1},\n",
69
+ " \"dropout_rate\": {\"type\": \"float\", \"low\": 0.0, \"high\": 0.7},\n",
70
+ " \"lr_scheduler_type\": {\"type\": \"categorical\", \"choices\": [\"cosine\"]},\n",
71
+ " \"task_weights\": {\"type\": \"float\", \"low\": 0.1, \"high\": 2.0}\n",
72
+ "}"
73
+ ]
74
+ },
75
+ {
76
+ "cell_type": "markdown",
77
+ "id": "31857690-a739-435a-aefd-f171fafc1b78",
78
+ "metadata": {},
79
+ "source": [
80
+ "In the code above, we've defined `task_columns` as `[\"cell_type\", \"disease_state\"]`. This means our model will be trained to classify cells based on two tasks:\n",
81
+ "1. Identifying the cell type\n",
82
+ "2. Determining the disease state\n",
83
+ "3. Note: \"unique_cell_id\" is a required column in the dataset for logging and inference purposes\n",
84
+ "\n",
85
+ "These column names should correspond to actual columns in your dataset. Each column should contain the labels for that specific classification task.\n",
86
+ "\n",
87
+ "For example, your dataset might look something like this:\n",
88
+ "\n",
89
+ " | unique_cell_id | input_ids | ... | cell_type | disease_state |\n",
90
+ " |----------------|-----------|-----|-----------|---------------|\n",
91
+ " | cell1 | ... | ... | neuron | healthy |\n",
92
+ " | cell2 | ... | ... | astrocyte | diseased |\n",
93
+ " | ... | ... | ... | ... | ... |\n",
94
+ "The model will learn to predict classes within 'cell_type' and 'disease_state' "
95
+ ]
96
+ },
97
+ {
98
+ "cell_type": "markdown",
99
+ "id": "b9e3050a-6162-4c01-b6fd-8784bf4ab1e4",
100
+ "metadata": {},
101
+ "source": [
102
+ "## 3. Initialize the MTLClassifier\n",
103
+ "\n",
104
+ "Now, let's create an instance of the MTLClassifier with our defined parameters and task columns."
105
+ ]
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "execution_count": null,
110
+ "id": "e27caac9-670c-409d-9313-50201c665cb9",
111
+ "metadata": {},
112
+ "outputs": [],
113
+ "source": [
114
+ "mc = MTLClassifier(\n",
115
+ " task_columns=task_columns, # Our defined classification tasks\n",
116
+ " study_name=\"MTLClassifier_example\",\n",
117
+ " pretrained_path=pretrained_path,\n",
118
+ " train_path=train_path,\n",
119
+ " val_path=val_path,\n",
120
+ " test_path=test_path,\n",
121
+ " model_save_path=model_save_path,\n",
122
+ " results_dir=results_dir,\n",
123
+ " tensorboard_log_dir=tensorboard_log_dir,\n",
124
+ " hyperparameters=hyperparameters,\n",
125
+ " n_trials=15, # Number of trials for hyperparameter optimization (at least 50 suggested)\n",
126
+ " epochs=1, # Number of training epochs (1 suggested to prevent overfitting)\n",
127
+ " batch_size=8, # Adjust based on available GPU memory\n",
128
+ " seed=42\n",
129
+ ")"
130
+ ]
131
+ },
132
+ {
133
+ "cell_type": "markdown",
134
+ "id": "0d729444-e3ad-4584-9659-0c464ac97462",
135
+ "metadata": {},
136
+ "source": [
137
+ "## 4. Run Hyperparameter Optimization\n",
138
+ "\n",
139
+ "Now, let's run the Optuna study to optimize our hyperparameters for both classification tasks."
140
+ ]
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "execution_count": null,
145
+ "id": "9298aa3e-6a52-4aa8-b9ff-b63d97beac93",
146
+ "metadata": {},
147
+ "outputs": [],
148
+ "source": [
149
+ "mc.run_optuna_study()"
150
+ ]
151
+ },
152
+ {
153
+ "cell_type": "markdown",
154
+ "id": "af23075d-d07b-43d3-bc5d-4df4d5d7199b",
155
+ "metadata": {},
156
+ "source": [
157
+ "## 5. Evaluate the Model on Test Data\n",
158
+ "\n",
159
+ "After optimization, we can evaluate our model on the test dataset. This will provide performance metrics for both classification tasks. CSV containing following keys will be generated in specified results directiory \"Cell ID, task(1...n) True,task(1.,.n) Pred,task(1...n) Probabilities\""
160
+ ]
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "execution_count": null,
165
+ "id": "461bf8d3-b964-4ff4-994f-9f3d313d4614",
166
+ "metadata": {},
167
+ "outputs": [],
168
+ "source": [
169
+ "mc.load_and_evaluate_test_model()"
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "markdown",
174
+ "id": "31cfeb2d-6673-4b02-a79c-2533cc5e4d28",
175
+ "metadata": {},
176
+ "source": [
177
+ "## 6. (Optional) Manual Hyperparameter Tuning\n",
178
+ "\n",
179
+ "If you prefer to set hyperparameters manually, you can use the following approach:"
180
+ ]
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "execution_count": null,
185
+ "id": "8ee6b99f-42e9-4abf-a292-aa9047735e0e",
186
+ "metadata": {},
187
+ "outputs": [],
188
+ "source": [
189
+ "manual_hyperparameters = {\n",
190
+ " \"learning_rate\": 0.001,\n",
191
+ " \"warmup_ratio\": 0.01,\n",
192
+ " \"weight_decay\": 0.1,\n",
193
+ " \"dropout_rate\": 0.1,\n",
194
+ " \"lr_scheduler_type\": \"cosine\",\n",
195
+ " \"task_weights\": [1, 1], # Weights for each task (cell_type, disease_state)\n",
196
+ " \"max_layers_to_freeze\": 2\n",
197
+ "}\n",
198
+ "\n",
199
+ "mc_manual = MTLClassifier(\n",
200
+ " task_columns=task_columns,\n",
201
+ " study_name=\"mtl_manual\",\n",
202
+ " pretrained_path=pretrained_path,\n",
203
+ " train_path=train_path,\n",
204
+ " val_path=val_path,\n",
205
+ " test_path=test_path,\n",
206
+ " model_save_path=model_save_path,\n",
207
+ " results_dir=results_dir,\n",
208
+ " tensorboard_log_dir=tensorboard_log_dir,\n",
209
+ " manual_hyperparameters=manual_hyperparameters,\n",
210
+ " use_manual_hyperparameters=True,\n",
211
+ " epochs=10,\n",
212
+ " batch_size=32,\n",
213
+ " seed=42\n",
214
+ ")\n",
215
+ "\n",
216
+ "mc_manual.run_manual_tuning()"
217
+ ]
218
+ },
219
+ {
220
+ "cell_type": "markdown",
221
+ "id": "dbaac008-fc00-4b71-8e78-89b2d922d9d8",
222
+ "metadata": {},
223
+ "source": [
224
+ "# Geneformer In Silico Perturber Tutorial (MTL Quantized)\n",
225
+ "This demonstrates how to use the Geneformer In Silico Perturber with a Multi-Task Learning (MTL) model in a quantized configuration to optimize runtime and memory."
226
+ ]
227
+ },
228
+ {
229
+ "cell_type": "code",
230
+ "execution_count": null,
231
+ "id": "2e15ad57-736c-48f0-be87-39cf5015bc5c",
232
+ "metadata": {},
233
+ "outputs": [],
234
+ "source": [
235
+ "from geneformer import InSilicoPerturber, EmbExtractor, InSilicoPerturberStats"
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "execution_count": null,
241
+ "id": "43c18140-151e-4d44-95b4-a9b3a47172cf",
242
+ "metadata": {},
243
+ "outputs": [],
244
+ "source": [
245
+ "# Define paths\n",
246
+ "model_directory = \"/path/to/model/save/path\"\n",
247
+ "input_data_file = \"/path/to/input/data.dataset\"\n",
248
+ "output_directory = \"/path/to/output/directory\"\n",
249
+ "output_prefix = \"mtl_quantized_perturbation\"\n",
250
+ "\n",
251
+ "# Define parameters\n",
252
+ "perturb_type = \"delete\" # or \"overexpress\"\n",
253
+ "\n",
254
+ "# Define cell states to model\n",
255
+ "cell_states_to_model = {\n",
256
+ " \"state_key\": \"disease_state\", \n",
257
+ " \"start_state\": \"disease\", \n",
258
+ " \"goal_state\": \"control\"\n",
259
+ "}\n",
260
+ "\n",
261
+ "# Define filter data\n",
262
+ "filter_data_dict = {\n",
263
+ " \"cell_type\": [\"Fibroblast\"]\n",
264
+ "}"
265
+ ]
266
+ },
267
+ {
268
+ "cell_type": "markdown",
269
+ "id": "3010d0bf-b23c-45c1-ac12-8c472dc8b7a1",
270
+ "metadata": {},
271
+ "source": [
272
+ "## 3. Extract State Embeddings\n",
273
+ "\n",
274
+ "Before we initialize the InSilicoPerturber, we need to extract the state embeddings using the EmbExtractor."
275
+ ]
276
+ },
277
+ {
278
+ "cell_type": "code",
279
+ "execution_count": null,
280
+ "id": "215f0a90-8041-417d-a5d3-b2483626c3b2",
281
+ "metadata": {},
282
+ "outputs": [],
283
+ "source": [
284
+ "# Initialize EmbExtractor\n",
285
+ "embex = EmbExtractor(\n",
286
+ " filter_data_dict=filter_data_dict,\n",
287
+ " max_ncells=1000, # Number of cells to extract embeddings for\n",
288
+ " emb_layer=0, # Use the second to last layer\n",
289
+ " emb_mode = \"cls\",\n",
290
+ " summary_stat=\"exact_mean\",\n",
291
+ " forward_batch_size=8, # Adjust based on available GPU memory\n",
292
+ " nproc=4\n",
293
+ ")\n",
294
+ "\n",
295
+ "# Extract state embeddings\n",
296
+ "state_embs_dict = embex.get_state_embs(\n",
297
+ " cell_states_to_model,\n",
298
+ " model_directory=model_directory,\n",
299
+ " input_data_file=input_data_file,\n",
300
+ " output_directory=output_directory,\n",
301
+ " output_prefix=output_prefix\n",
302
+ ")"
303
+ ]
304
+ },
305
+ {
306
+ "cell_type": "markdown",
307
+ "id": "23f14e36-4529-4fb2-8af9-7f4875cf81e3",
308
+ "metadata": {},
309
+ "source": [
310
+ "## 4. Initialize the InSilicoPerturber\n",
311
+ "\n",
312
+ "Now that we have our state embeddings, let's create an instance of the InSilicoPerturber with MTL and quantized configurations."
313
+ ]
314
+ },
315
+ {
316
+ "cell_type": "code",
317
+ "execution_count": null,
318
+ "id": "09f985a1-91bc-4e8d-8001-a3663531b570",
319
+ "metadata": {},
320
+ "outputs": [],
321
+ "source": [
322
+ "# Initialize InSilicoPerturber\n",
323
+ "isp = InSilicoPerturber(\n",
324
+ " perturb_type=perturb_type,\n",
325
+ " genes_to_perturb=\"all\", # Perturb all genes\n",
326
+ " model_type=\"MTLCellClassifier-Quantized\", # Use quantized MTL model\n",
327
+ " emb_mode=\"cls\", # Use CLS token embedding\n",
328
+ " cell_states_to_model=cell_states_to_model,\n",
329
+ " state_embs_dict=state_embs_dict,\n",
330
+ " max_ncells=1000, # Number of cells to perturb (larger number increases power)\n",
331
+ " emb_layer=0, \n",
332
+ " forward_batch_size=8, # Adjust based on available GPU memory\n",
333
+ " nproc=1\n",
334
+ ")"
335
+ ]
336
+ },
337
+ {
338
+ "cell_type": "markdown",
339
+ "id": "cfcc2c1e-fd7f-4a36-99fc-ac7f43e5be6b",
340
+ "metadata": {},
341
+ "source": [
342
+ "## 5. Run In Silico Perturbation\n",
343
+ "\n",
344
+ "Run the in silico perturbation on the dataset."
345
+ ]
346
+ },
347
+ {
348
+ "cell_type": "code",
349
+ "execution_count": null,
350
+ "id": "cf030c09-8ae4-45a7-aaf7-3fc2af4fe296",
351
+ "metadata": {},
352
+ "outputs": [],
353
+ "source": [
354
+ "# Run perturbation and output intermediate files\n",
355
+ "isp.perturb_data(\n",
356
+ " model_directory=model_directory,\n",
357
+ " input_data_file=input_data_file,\n",
358
+ " output_directory=output_directory,\n",
359
+ " output_prefix=output_prefix\n",
360
+ ")"
361
+ ]
362
+ },
363
+ {
364
+ "cell_type": "markdown",
365
+ "id": "bb8ec074-6f2f-422b-a973-37ed32a15c38",
366
+ "metadata": {},
367
+ "source": [
368
+ "## 6. Process Results with InSilicoPerturberStats\n",
369
+ "\n",
370
+ "After running the perturbation, we'll use InSilicoPerturberStats to process the intermediate files and generate the final statistics."
371
+ ]
372
+ },
373
+ {
374
+ "cell_type": "code",
375
+ "execution_count": null,
376
+ "id": "0a748043-43fc-47ad-ace5-f0ae3dd34674",
377
+ "metadata": {},
378
+ "outputs": [],
379
+ "source": [
380
+ "# Initialize InSilicoPerturberStats\n",
381
+ "ispstats = InSilicoPerturberStats(\n",
382
+ " mode=\"goal_state_shift\",\n",
383
+ " genes_perturbed=\"all\",\n",
384
+ " combos=0,\n",
385
+ " anchor_gene=None,\n",
386
+ " cell_states_to_model=cell_states_to_model\n",
387
+ ")\n",
388
+ "\n",
389
+ "# Process stats and output final .csv\n",
390
+ "ispstats.get_stats(\n",
391
+ " input_data_file,\n",
392
+ " None,\n",
393
+ " output_directory,\n",
394
+ " output_prefix\n",
395
+ ")"
396
+ ]
397
+ }
398
+ ],
399
+ "metadata": {
400
+ "kernelspec": {
401
+ "display_name": "Python 3 (ipykernel)",
402
+ "language": "python",
403
+ "name": "python3"
404
+ },
405
+ "language_info": {
406
+ "codemirror_mode": {
407
+ "name": "ipython",
408
+ "version": 3
409
+ },
410
+ "file_extension": ".py",
411
+ "mimetype": "text/x-python",
412
+ "name": "python",
413
+ "nbconvert_exporter": "python",
414
+ "pygments_lexer": "ipython3",
415
+ "version": "3.11.5"
416
+ }
417
+ },
418
+ "nbformat": 4,
419
+ "nbformat_minor": 5
420
+ }