mineself2016 commited on
Commit
fedc59c
·
verified ·
1 Parent(s): 8e0d6fb

Remove stale path: examples/legacy_from_gene_mamba/mamba2_classification_finetune_with_label.py

Browse files
examples/legacy_from_gene_mamba/mamba2_classification_finetune_with_label.py DELETED
@@ -1,378 +0,0 @@
1
- # %%
2
- import torch
3
- from transformers import Trainer
4
- import os
5
-
6
- import pyarrow as pa
7
- import pandas as pd
8
- import numpy as np
9
-
10
- from matplotlib import pyplot as plt
11
-
12
- from torch.utils.data import Dataset
13
- from transformers import AutoTokenizer, TrainingArguments
14
-
15
- import argparse
16
-
17
- from mamba_ssm.models.mixer_seq_simple import MambaLMHeadModel
18
- from transformers import AutoTokenizer, TrainingArguments, MambaForCausalLM
19
-
20
- from dotmap import DotMap
21
-
22
- import sys
23
- import os
24
- import torch
25
-
26
- # from trange import trange
27
-
28
- sys.path.append("/project/zhiwei/cq5/PythonWorkSpace/gene_mamba")
29
- from models import Classifier, GeneMamba, GeneMambaForCellAnnotation, GeneMambaForGeneClassification, GeneMamba2, GeneMamba2ForCellClassification
30
- from utils import permute_genes_by_expression
31
- from utils2 import standardize_columns
32
-
33
- import importlib
34
- importlib.reload(sys.modules['models'])
35
- importlib.reload(sys.modules['utils'])
36
- importlib.reload(sys.modules['utils2'])
37
-
38
-
39
- # %%
40
- DATA_PATH = "/project/zhiwei/cq5/PythonWorkSpace/gene_mamba/dataset/downstream/"
41
- # CHECKPOINT_PATH = "/project/zhiwei/cq5/LLM_checkpoints/GeneMamba/GeneMamba2_48l_512d/1/3m/checkpoint-31250"
42
- TOKENIZER_PATH = "/project/zhiwei/cq5/PythonWorkSpace/gene_mamba/gene_tokenizer.json"
43
- SAVE_PATH = "/project/zhiwei/cq5/PythonWorkSpace/gene_mamba/dataset/embeddings/cell"
44
-
45
- # %%
46
- import argparse
47
-
48
- parser = argparse.ArgumentParser()
49
- parser.add_argument("--dataset_name", type=str)
50
- parser.add_argument("--ckpt_path", type = str)
51
- parser.add_argument("--seq_len", type=int, default=2048)
52
- parser.add_argument("--batch_size", type=int, default=24)
53
- parser.add_argument("--num_epochs", type=int, default=5)
54
- parser.add_argument("--test_size", type = float, default=0.1)
55
- parser.add_argument("--split", type=lambda x: x.lower() in ["true", "1", "yes"], default=False,)
56
-
57
- args = parser.parse_args()
58
-
59
-
60
- # args = DotMap({
61
- # "dataset_name": "ms",
62
- # "seq_len": 512,
63
- # "batch_size": 24,
64
- # "num_epochs": 5,
65
- # "test_size": 0.1
66
- # })
67
-
68
-
69
- #%%
70
- CHECKPOINT_PATH = args.ckpt_path
71
- model_name = CHECKPOINT_PATH.split("/")[-4]
72
- mamba_layer = int(model_name.split("_")[1][:-1])
73
- d_model = int(model_name.split("_")[2][:-1])
74
-
75
-
76
- # make the sub directories to save the results
77
- SAVE_PATH = os.path.join(SAVE_PATH, model_name)
78
- sub_directories = ["predictions", "metrics", "figures", "repr"]
79
- for sub_dir in sub_directories:
80
- os.makedirs(os.path.join(SAVE_PATH, sub_dir), exist_ok=True)
81
-
82
-
83
- # %%
84
- import scanpy as sc
85
-
86
- # Load the .h5ad file
87
- dataset_name = args.dataset_name
88
- # adata = sc.read_h5ad(os.path.join(DATA_PATH ,f'{dataset_name}.h5ad'))
89
-
90
- adata = None
91
-
92
- if args.split:
93
- adata = sc.read_h5ad(os.path.join(DATA_PATH ,f'split/{dataset_name}_split.h5ad'))
94
- print(f"Read data from {dataset_name}_split.h5ad")
95
- dataset_name = dataset_name + "_split"
96
- else:
97
- adata = sc.read_h5ad(os.path.join(DATA_PATH ,f'processed/{dataset_name}_processed.h5ad'))
98
- print(f"Read data from {dataset_name}_processed.h5ad")
99
-
100
- # Display basic information about the data
101
- print(adata)
102
-
103
- # %%
104
- # adata = standardize_columns(adata, dataset_name)
105
- # assert "batch" in adata.obs.columns and "celltype" in adata.obs.columns
106
-
107
- # %%
108
- from sklearn.preprocessing import LabelEncoder
109
-
110
- y_names = np.array(adata.obs['celltype'].values.tolist())
111
-
112
- label_encoder = LabelEncoder()
113
- y = label_encoder.fit_transform(y_names)
114
-
115
- num_class = len(label_encoder.classes_)
116
-
117
- # %%
118
- from transformers import PretrainedConfig
119
-
120
- config = PretrainedConfig.from_dict({
121
- "d_model": d_model,
122
- "mamba_layer": mamba_layer,
123
- })
124
-
125
-
126
- # %%
127
- model_cell_cls = GeneMamba2ForCellClassification(config, model_path=CHECKPOINT_PATH, tokenizer_path = TOKENIZER_PATH, args=None, output_dim_cls = num_class, hidden_dim= 512, num_layers_cls = 4)
128
-
129
- # %%
130
- permuted_gene_ids = permute_genes_by_expression(adata, dataset_name, model_cell_cls.tokenizer, model_cell_cls.symbol2id)
131
- permuted_gene_ids
132
-
133
- # %%
134
- seq_len = args.seq_len
135
-
136
- input_data = permuted_gene_ids[:, :seq_len]
137
-
138
- # %%
139
- model_cell_cls.tokenizer.cls_token_id
140
-
141
- # %%
142
- torch.tensor([model_cell_cls.tokenizer.cls_token_id for _ in range(input_data.shape[0])])
143
-
144
- # %%
145
- model_cell_cls.tokenizer.cls_token_id
146
-
147
- # %%
148
- input_data.shape[0]
149
-
150
- # %%
151
- input_data
152
-
153
- # %%
154
- # add the cls token to the input data
155
- input_data = np.hstack([np.array([model_cell_cls.tokenizer.cls_token_id for _ in range(input_data.shape[0])]).reshape(-1, 1), input_data])
156
- input_data
157
-
158
- # %%
159
- input_data.shape
160
-
161
- #%%
162
- from sklearn.model_selection import train_test_split
163
- import numpy as np
164
-
165
- def manual_stratified_split(X, y, test_size=0.1, random_state=None):
166
- # separate the samples for each class
167
- unique_classes = np.unique(y)
168
- X_train, X_test, y_train, y_test = [], [], [], []
169
-
170
- for cls in unique_classes:
171
- cls_indices = np.where(y == cls)[0]
172
-
173
- if len(cls_indices) > 1:
174
-
175
- cls_train, cls_test = train_test_split(cls_indices, test_size=test_size, random_state=random_state)
176
- else:
177
- # if a class has only one sample, put it in the training set
178
- cls_train, cls_test = cls_indices, []
179
-
180
- X_train.extend(X[cls_train])
181
- y_train.extend(y[cls_train])
182
- X_test.extend(X[cls_test])
183
- y_test.extend(y[cls_test])
184
-
185
- return np.array(X_train), np.array(X_test), np.array(y_train), np.array(y_test)
186
-
187
- # %%
188
- # from sklearn.model_selection import train_test_split
189
-
190
- # X_train, X_test, y_train, y_test = manual_stratified_split(input_data, y, test_size=args.test_size, random_state=42)
191
-
192
-
193
- #%%
194
- # train and test split is done and stored in the adata.obs["partition"] column, so we can extract the train and test data from there
195
-
196
- X_train = input_data[adata.obs["partition"] == "train"]
197
- X_test = input_data[adata.obs["partition"] == "test"]
198
- y_train = y[adata.obs["partition"] == "train"]
199
- y_test = y[adata.obs["partition"] == "test"]
200
-
201
- X_train.shape, X_test.shape, y_train.shape, y_test.shape
202
-
203
- # %%
204
- from torch.utils.data import DataLoader, Dataset
205
-
206
- class GeneDataset(Dataset):
207
- def __init__(self, data, y):
208
- self.data = data
209
- self.labels = y
210
-
211
- def __len__(self):
212
- return len(self.data)
213
-
214
- def __getitem__(self, idx):
215
- return self.data[idx], self.labels[idx]
216
-
217
- train_dataset = GeneDataset(X_train, y_train)
218
- test_dataset = GeneDataset(X_test, y_test)
219
- all_dataset = GeneDataset(input_data, y)
220
-
221
- train_loader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True)
222
- test_loader = DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False)
223
- all_loader = DataLoader(all_dataset, batch_size=args.batch_size, shuffle=False)
224
-
225
- # %%
226
- from sklearn.metrics import classification_report, accuracy_score, f1_score, precision_score, recall_score, roc_auc_score
227
-
228
- # %%
229
- def compute_metrics(y_pred, y_prob, y_true):
230
-
231
- metrics = {
232
- "accuracy": accuracy_score(y_true, y_pred),
233
- "Micro-F1 score": f1_score(y_true, y_pred, average='micro'),
234
- "Macro-F1 score": f1_score(y_true, y_pred, average='macro'),
235
- "precision": precision_score(y_true, y_pred, average='weighted'),
236
- "recall": recall_score(y_true, y_pred, average='weighted'),
237
- # "auc_roc": roc_auc_score(y_true, y_prob, multi_class = 'ovr'),
238
- }
239
- return metrics
240
-
241
- # %%
242
- epochs = args.num_epochs
243
- optimizer = torch.optim.Adam(model_cell_cls.parameters(), lr=1e-4)
244
- loss = torch.nn.CrossEntropyLoss()
245
-
246
- for epoch in range(epochs):
247
- model_cell_cls.train()
248
- for i, batch in enumerate(train_loader):
249
- data = batch[0]
250
- target = batch[1]
251
- data = data.to(model_cell_cls.device)
252
- target = target.to(model_cell_cls.device)
253
- model_cell_cls = model_cell_cls.to(model_cell_cls.device)
254
-
255
- optimizer.zero_grad()
256
- output = model_cell_cls(data, None)
257
- loss_val = loss(output, target)
258
- loss_val.backward()
259
- optimizer.step()
260
- if i % 10 == 0:
261
- print(f"Epoch {epoch}, Iteration {i}, Loss: {loss_val}")
262
-
263
- model_cell_cls.eval()
264
- with torch.no_grad():
265
- # add code to compute the metrics
266
- pred_prob = []
267
- pred_label = []
268
- targets = []
269
- cell_repr = []
270
-
271
- for i, batch in enumerate(test_loader):
272
- data = batch[0]
273
- target = batch[1]
274
- data = data.to(model_cell_cls.device)
275
- target = target.to(model_cell_cls.device)
276
- model_cell_cls = model_cell_cls.to(model_cell_cls.device)
277
-
278
- output, output_test_repr = model_cell_cls(data, None, return_cls = True)
279
- cell_repr.append(output_test_repr.cpu().numpy())
280
-
281
- # calculate the probability from the output
282
- pred_prob.append(torch.nn.functional.softmax(output, dim=1).cpu().numpy())
283
-
284
- _, predicted = torch.max(output, 1)
285
- pred_label.append(predicted.cpu().numpy())
286
- targets.append(target.cpu().numpy())
287
-
288
- pred_prob = np.concatenate(pred_prob)
289
- pred_label = np.concatenate(pred_label)
290
- targets = np.concatenate(targets)
291
- cell_repr = np.concatenate(cell_repr)
292
-
293
- # break
294
- # save the predictions
295
- np.save(os.path.join(SAVE_PATH, f"predictions/pred_prob_{dataset_name}_{epoch}.npy"), pred_prob)
296
- np.save(os.path.join(SAVE_PATH, f"predictions/pred_label_{dataset_name}_{epoch}.npy"), pred_label)
297
- np.save(os.path.join(SAVE_PATH, f"predictions/targets_{dataset_name}_{epoch}.npy"), targets)
298
-
299
- metrics = compute_metrics(pred_label, pred_prob, targets)
300
-
301
- with open(os.path.join(SAVE_PATH, f"metrics/metrics_{dataset_name}_{epoch}.txt"), "w") as f:
302
- print(metrics, file=f)
303
- print(metrics)
304
-
305
-
306
- # draw scatter plot for the first two components
307
- from sklearn.decomposition import PCA
308
-
309
- pca = PCA(n_components=2)
310
- pca_result = pca.fit_transform(cell_repr)
311
-
312
- plt.figure(figsize=(8, 8))
313
-
314
- plt.scatter(pca_result[:, 0], pca_result[:, 1], c = targets)
315
- plt.savefig(os.path.join(SAVE_PATH, f"figures/scatter_{dataset_name}_{epoch}.png"))
316
- # plt.show()
317
-
318
-
319
- # %%
320
- model_cell_cls.eval()
321
-
322
- def cell_embeddings(data_loader, model_cell_cls):
323
- cell_repr = []
324
-
325
- for i, batch in enumerate(data_loader):
326
- data = batch[0]
327
- target = batch[1]
328
- data = data.to(model_cell_cls.device)
329
- target = target.to(model_cell_cls.device)
330
- model_cell_cls = model_cell_cls.to(model_cell_cls.device)
331
-
332
- output, output_test_repr = model_cell_cls(data, None, return_cls = True)
333
- cell_repr.append(output_test_repr.detach().cpu().numpy())
334
- if i % 10 == 0:
335
- print(f"Processed {i} batches")
336
-
337
- cell_repr = np.concatenate(cell_repr)
338
- return cell_repr
339
-
340
-
341
- test_cell_repr = cell_embeddings(test_loader, model_cell_cls)
342
- save_path_test = os.path.join(SAVE_PATH, f"repr/{dataset_name}_test_cell_repr.npy")
343
- np.save(save_path_test, test_cell_repr)
344
- del test_cell_repr
345
-
346
-
347
- train_cell_repr = cell_embeddings(train_loader, model_cell_cls)
348
- save_path_train = os.path.join(SAVE_PATH, f"repr/{dataset_name}_train_cell_repr.npy")
349
- np.save(save_path_train, train_cell_repr)
350
- del train_cell_repr
351
-
352
- all_cell_repr = cell_embeddings(all_loader, model_cell_cls)
353
- save_path_all = os.path.join(SAVE_PATH, f"repr/{dataset_name}_cell_repr.npy")
354
- np.save(save_path_all, all_cell_repr)
355
- del all_cell_repr
356
-
357
-
358
- # %%
359
- # original_data = adata.X.toarray()
360
- # original_data.shape
361
-
362
- # %%
363
- # draw the scatter figure on the original data
364
- # from sklearn.decomposition import PCA
365
-
366
- # pca = PCA(n_components=2)
367
- # pca_result = pca.fit_transform(original_data)
368
-
369
- # plt.figure(figsize=(8, 8))
370
-
371
- # plt.scatter(pca_result[:, 0], pca_result[:, 1], c = y)
372
- # plt.show()
373
-
374
-
375
- # %%
376
-
377
-
378
-