OpenSpliceai 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. OpenSpliceai-0.0.1.dist-info/LICENSE +674 -0
  2. OpenSpliceai-0.0.1.dist-info/METADATA +177 -0
  3. OpenSpliceai-0.0.1.dist-info/RECORD +42 -0
  4. OpenSpliceai-0.0.1.dist-info/WHEEL +5 -0
  5. OpenSpliceai-0.0.1.dist-info/entry_points.txt +2 -0
  6. OpenSpliceai-0.0.1.dist-info/top_level.txt +1 -0
  7. openspliceai/__init__.py +1 -0
  8. openspliceai/calibrate/__init__.py +0 -0
  9. openspliceai/calibrate/calibrate.py +85 -0
  10. openspliceai/calibrate/calibrate_utils.py +42 -0
  11. openspliceai/calibrate/model_utils.py +59 -0
  12. openspliceai/calibrate/temperature_scaling.py +211 -0
  13. openspliceai/calibrate/visualization.py +99 -0
  14. openspliceai/constants.py +14 -0
  15. openspliceai/create_data/__init__.py +0 -0
  16. openspliceai/create_data/create_datafile.py +159 -0
  17. openspliceai/create_data/create_dataset.py +64 -0
  18. openspliceai/create_data/paralogs.py +81 -0
  19. openspliceai/create_data/utils.py +254 -0
  20. openspliceai/create_data/verify_h5_file.py +61 -0
  21. openspliceai/header.py +11 -0
  22. openspliceai/merge_data/__init__.py +0 -0
  23. openspliceai/merge_data/merge_dataset.py +103 -0
  24. openspliceai/openspliceai.py +197 -0
  25. openspliceai/predict/__init__.py +0 -0
  26. openspliceai/predict/predict.py +1091 -0
  27. openspliceai/predict/utils.py +53 -0
  28. openspliceai/test/__init__.py +0 -0
  29. openspliceai/test/spliceai.py +45 -0
  30. openspliceai/test/test.py +92 -0
  31. openspliceai/train/__init__.py +0 -0
  32. openspliceai/train/train.py +76 -0
  33. openspliceai/train_base/__init__.py +0 -0
  34. openspliceai/train_base/spliceai.py +61 -0
  35. openspliceai/train_base/utils.py +644 -0
  36. openspliceai/transfer/__init__.py +0 -0
  37. openspliceai/transfer/transfer.py +107 -0
  38. openspliceai/variant/__init__.py +0 -0
  39. openspliceai/variant/get_anno.py +129 -0
  40. openspliceai/variant/test.py +31 -0
  41. openspliceai/variant/utils.py +541 -0
  42. openspliceai/variant/variant.py +89 -0
@@ -0,0 +1,644 @@
1
+ import h5py
2
+ import platform
3
+ import sys
4
+ import os
5
+ import time
6
+ import numpy as np
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.optim as optim
10
+ from torch.utils.data import TensorDataset, DataLoader
11
+ from tqdm import tqdm
12
+ from math import ceil
13
+ from sklearn.metrics import average_precision_score, precision_recall_fscore_support, accuracy_score
14
+ from openspliceai.constants import *
15
+
16
+ def setup_environment(args):
17
+ assert int(args.flanking_size) in [80, 400, 2000, 10000]
18
+ device = setup_device()
19
+ print("device: ", device, file=sys.stderr)
20
+ return device
21
+
22
+ ###########################
23
+ # Model testing
24
+ ###########################
25
+ def initialize_test_paths(args):
26
+ log_output_test_base = initialize_test_paths_inner(
27
+ args.output_dir, args.project_name, args.flanking_size, args.exp_num,
28
+ args.random_seed, args.test_target, args.log_dir
29
+ )
30
+ return log_output_test_base
31
+
32
+
33
+ def initialize_test_paths_inner(output_dir, project_name, flanking_size, exp_num, random_seed, test_target, log_dir):
34
+ MODEL_VERSION = f"SpliceAI_{project_name}_{flanking_size}_{exp_num}_rs{random_seed}"
35
+ model_train_outdir = f"{output_dir}/{MODEL_VERSION}/{exp_num}/"
36
+ log_output_base = f"{model_train_outdir}{log_dir}/"
37
+ log_output_test_base = f"{log_output_base}TEST/"
38
+ # TEST_LOG_SpliceAI-Keras
39
+ for path in [log_output_base, log_output_test_base]:
40
+ os.makedirs(path, exist_ok=True)
41
+ return log_output_test_base
42
+
43
+
44
+ def load_test_datasets(args):
45
+ test_h5f = h5py.File(args.test_dataset, 'r')
46
+ return test_h5f
47
+
48
+
49
+ def generate_test_indices(random_seed, test_h5f):
50
+ np.random.seed(random_seed)
51
+ test_idxs = np.arange(len(test_h5f.keys()) // 2)
52
+ np.random.shuffle(test_idxs)
53
+ return test_idxs
54
+
55
+
56
+ def clip_datapoints_spliceai27(X, Y, CL, N_GPUS):
57
+ rem = X.shape[0]%N_GPUS
58
+ clip = (CL_max-CL)//2
59
+ if rem != 0 and clip != 0:
60
+ return X[:-rem, clip:-clip], [Y[t][:-rem] for t in range(1)]
61
+ elif rem == 0 and clip != 0:
62
+ return X[:, clip:-clip], [Y[t] for t in range(1)]
63
+ elif rem != 0 and clip == 0:
64
+ return X[:-rem], [Y[t][:-rem] for t in range(1)]
65
+ else:
66
+ return X, [Y[t] for t in range(1)]
67
+
68
+
69
+ class MetricsAccumulator:
70
+ def __init__(self, num_classes):
71
+ self.true_classes = []
72
+ self.predicted_classes = []
73
+ self.num_classes = num_classes
74
+
75
+ def update(self, y_true, y_pred):
76
+ self.true_classes.extend(y_true)
77
+ self.predicted_classes.extend(y_pred)
78
+
79
+ def calculate_overall_metrics(self):
80
+ true_classes = np.array(self.true_classes)
81
+ predicted_classes = np.array(self.predicted_classes)
82
+ true_classes = true_classes.flatten()
83
+ predicted_classes = predicted_classes.flatten()
84
+ print(f"true_classes: {true_classes.shape}, predicted_classes: {predicted_classes.shape}")
85
+
86
+
87
+ class_accuracies = classwise_accuracy(true_classes, predicted_classes, self.num_classes)
88
+ overall_accuracy = np.mean(class_accuracies)
89
+
90
+ precision, recall, f1, _ = precision_recall_fscore_support(true_classes, predicted_classes, average=None)
91
+
92
+ return overall_accuracy, precision, recall, f1, class_accuracies
93
+
94
+
95
+ def calculate_batch_metrics(y_true, y_pred, metric_files, accumulator):
96
+ accumulator.update(y_true, y_pred)
97
+ batch_accuracies = classwise_accuracy(y_true, y_pred, accumulator.num_classes)
98
+ batch_overall_accuracy = np.mean(batch_accuracies)
99
+ print(f"Batch Overall Accuracy: {batch_overall_accuracy}")
100
+
101
+
102
+ def process_batch(model, X, Y, params):
103
+ Xc, Yc = clip_datapoints_spliceai27(X, Y, params['CL'], 2)
104
+ Yp = model.predict(Xc, batch_size=params['BATCH_SIZE'])
105
+ return Yc[0], Yp
106
+
107
+
108
+ def test_SpliceAI_Keras_model(model, test_h5f, test_idxs, args, params, test_metric_files):
109
+ print("test_idxs: ", test_idxs)
110
+ print(f"\n{'='*60}")
111
+ start_time = time.time()
112
+ print("--------------------------------------------------------------")
113
+ print("\n\033[1mValidation set metrics:\033[0m")
114
+
115
+ np.random.seed(params["RANDOM_SEED"])
116
+ shuffled_idxs = np.random.choice(test_idxs, size=len(test_idxs), replace=False)
117
+ print("shuffled_idxs: ", shuffled_idxs)
118
+
119
+ shuffled_idxs = shuffled_idxs # For testing purposes
120
+ batch_size = 5 # Adjust this based on your memory constraints
121
+ num_classes = 3 # Assuming 3 classes: Non-splice, acceptor, donor
122
+ metrics_accumulator = MetricsAccumulator(num_classes)
123
+
124
+ # Initialize lists to collect true labels and predicted probabilities
125
+ y_true_acceptor_all = []
126
+ y_pred_acceptor_all = []
127
+ y_true_donor_all = []
128
+ y_pred_donor_all = []
129
+
130
+ for i in range(0, len(shuffled_idxs), batch_size):
131
+ batch_idxs = shuffled_idxs[i:i+batch_size]
132
+ batch_ylabel = []
133
+ batch_ypred = []
134
+
135
+ for idx in batch_idxs:
136
+ X = test_h5f['X' + str(idx)][()] # Assuming HDF5 dataset; read data
137
+ Y = test_h5f['Y' + str(idx)][()]
138
+ print(f"\nProcessing index {idx}:")
139
+ print(f"\tX.shape: {X.shape}, Y.shape: {Y.shape}")
140
+ Xc, Yc = clip_datapoints_spliceai27(X, Y, params['CL'], 2)
141
+ Yp = model.predict(Xc, batch_size=params['BATCH_SIZE'])
142
+ batch_ylabel.append(Yc[0]) # Yc is a list; take the first element
143
+ batch_ypred.append(Yp)
144
+ batch_ylabel = np.concatenate(batch_ylabel, axis=0)
145
+ batch_ypred = np.concatenate(batch_ypred, axis=0)
146
+ print(f"\nBatch shapes - ylabel: {batch_ylabel.shape}, ypred: {batch_ypred.shape}")
147
+
148
+ # Reshape to 2D arrays if necessary
149
+ batch_ylabel = batch_ylabel.reshape(-1, num_classes)
150
+ batch_ypred = batch_ypred.reshape(-1, num_classes)
151
+
152
+ # Extract true labels and predictions for acceptor and donor
153
+ y_true_acceptor = batch_ylabel[:, 1] # Acceptor class index is 1
154
+ y_pred_acceptor = batch_ypred[:, 1]
155
+ y_true_donor = batch_ylabel[:, 2] # Donor class index is 2
156
+ y_pred_donor = batch_ypred[:, 2]
157
+
158
+ # Accumulate the labels and predictions
159
+ y_true_acceptor_all.append(y_true_acceptor)
160
+ y_pred_acceptor_all.append(y_pred_acceptor)
161
+ y_true_donor_all.append(y_true_donor)
162
+ y_pred_donor_all.append(y_pred_donor)
163
+
164
+ # Convert probabilities to class predictions
165
+ batch_ypred_classes = np.argmax(batch_ypred, axis=-1)
166
+ batch_ylabel_classes = np.argmax(batch_ylabel, axis=-1)
167
+ calculate_batch_metrics(batch_ylabel_classes, batch_ypred_classes, test_metric_files, metrics_accumulator)
168
+ # Clear variables to free up memory
169
+ del batch_ylabel_classes, batch_ypred_classes
170
+
171
+ # Concatenate all batches
172
+ y_true_acceptor_all = np.concatenate(y_true_acceptor_all)
173
+ y_pred_acceptor_all = np.concatenate(y_pred_acceptor_all)
174
+ y_true_donor_all = np.concatenate(y_true_donor_all)
175
+ y_pred_donor_all = np.concatenate(y_pred_donor_all)
176
+
177
+ # Specify file paths for output
178
+ acceptor_topl_file = test_metric_files.get('acceptor_topl', 'acceptor_topl.txt')
179
+ donor_topl_file = test_metric_files.get('donor_topl', 'donor_topl.txt')
180
+
181
+ acceptor_topk_accuracy, acceptor_auprc = print_topl_statistics(y_true_donor_all, y_pred_donor_all, test_metric_files["acceptor_topk_all"], ss_type='acceptor', print_top_k=True)
182
+ donor_topk_accuracy, donor_auprc = print_topl_statistics(y_true_donor_all, y_pred_donor_all, test_metric_files["donor_topk_all"], ss_type='donor', print_top_k=True)
183
+
184
+ # Calculate and write overall metrics
185
+ overall_accuracy, precision, recall, f1, class_accuracies = metrics_accumulator.calculate_overall_metrics()
186
+ print(f"Overall Accuracy: {overall_accuracy:.4f}")
187
+ for k, v in test_metric_files.items():
188
+ with open(v, 'a') as f:
189
+ if k == "accuracy":
190
+ f.write(f"{overall_accuracy}\n")
191
+ elif k == "donor_topk":
192
+ f.write(f"{donor_topk_accuracy}\n")
193
+ elif k == "donor_auprc":
194
+ f.write(f"{donor_auprc}\n")
195
+ elif k == "acceptor_topk":
196
+ f.write(f"{acceptor_topk_accuracy}\n")
197
+ elif k == "acceptor_auprc":
198
+ f.write(f"{acceptor_auprc}\n")
199
+
200
+ ss_types = ["Non-splice", "acceptor", "donor"]
201
+ for i, (acc, prec, rec, f1_score) in enumerate(zip(class_accuracies, precision, recall, f1)):
202
+ print(f"Class {ss_types[i]}:\tAccuracy={acc:.4f}, Precision={prec:.4f}, Recall={rec:.4f}, F1={f1_score:.4f}")
203
+ if ss_types[i] == "Non-splice":
204
+ continue # Skip writing metrics for Non-splice class
205
+ for k, v in test_metric_files.items():
206
+ with open(v, 'a') as f:
207
+ if k == f"{ss_types[i]}_precision":
208
+ f.write(f"{prec}\n")
209
+ elif k == f"{ss_types[i]}_recall":
210
+ f.write(f"{rec}\n")
211
+ elif k == f"{ss_types[i]}_f1":
212
+ f.write(f"{f1_score}\n")
213
+ elif k == f"{ss_types[i]}_accuracy":
214
+ f.write(f"{acc}\n")
215
+ print("--------------------------------------------------------------")
216
+ print(f"--- {time.time() - start_time:.2f} seconds ---")
217
+ print("="*60)
218
+
219
+
220
+ def test_model(model, optimizer, test_h5f, test_idxs, args, device, params, test_metric_files):
221
+ print("test_idxs: ", test_idxs)
222
+ print(f"\n{'='*60}")
223
+ start_time = time.time()
224
+ test_loss = valid_epoch(model, test_h5f, test_idxs, params["BATCH_SIZE"], args.loss, device,
225
+ params, test_metric_files, args.flanking_size, "test")
226
+ print(f"Testing Loss: {test_loss}")
227
+ print(f"--- {time.time() - start_time:.2f} seconds ---")
228
+ print("="*60)
229
+
230
+
231
+ ###########################
232
+ # Model training
233
+ ###########################
234
+ def initialize_paths(args):
235
+ model_output_base, log_output_train_base, log_output_val_base, log_output_test_base = initialize_paths_inner(
236
+ args.output_dir, args.project_name, args.flanking_size, args.exp_num, SL, args.loss, args.random_seed
237
+ )
238
+ return model_output_base, log_output_train_base, log_output_val_base, log_output_test_base
239
+
240
+
241
+ def load_datasets(args):
242
+ train_h5f = h5py.File(args.train_dataset, 'r')
243
+ test_h5f = h5py.File(args.test_dataset, 'r')
244
+ batch_num = len(train_h5f.keys()) // 2
245
+ print("* Batch_num: ", batch_num, file=sys.stderr)
246
+ return train_h5f, test_h5f, batch_num
247
+
248
+
249
+ def generate_indices(batch_num, random_seed, test_h5f):
250
+ np.random.seed(random_seed)
251
+ idxs = np.random.permutation(batch_num)
252
+ train_idxs = idxs[:int(0.9 * batch_num)]
253
+ val_idxs = idxs[int(0.9 * batch_num):]
254
+ test_idxs = np.arange(len(test_h5f.keys()) // 2)
255
+ # # Generate and shuffle indices for training set
256
+ # train_idxs = np.arange(batch_num)
257
+ # np.random.shuffle(train_idxs)
258
+ # # Generate indices for test set
259
+ # test_idxs = np.arange(len(test_h5f.keys()) // 2)
260
+ # np.random.shuffle(test_idxs)
261
+ # # Split test set into test and validation
262
+ # val_size = int(0.5 * len(test_idxs)) # 10% for validation
263
+ # val_idxs = test_idxs[:val_size]
264
+ # test_idxs = test_idxs[val_size:]
265
+ return train_idxs, val_idxs, test_idxs
266
+
267
+
268
+ def create_metric_files(log_output_base):
269
+ metric_types = ['donor_topk_all', 'donor_topk', 'donor_auprc', 'donor_accuracy', 'donor_precision',
270
+ 'donor_recall', 'donor_f1', 'acceptor_topk_all', 'acceptor_topk', 'acceptor_auprc',
271
+ 'acceptor_accuracy', 'acceptor_precision', 'acceptor_recall', 'acceptor_f1',
272
+ 'accuracy', 'loss_batch', 'loss_every_update', 'learning_rate_every_epoch', 'learning_rate_every_batch']
273
+ return {metric: f'{log_output_base}/{metric}.txt' for metric in metric_types}
274
+
275
+
276
+ def setup_device():
277
+ device_str = "cuda" if torch.cuda.is_available() else "mps" if platform.system() == "Darwin" else "cpu"
278
+ return torch.device(device_str)
279
+
280
+
281
+ def initialize_paths_inner(output_dir, project_name, flanking_size, exp_num, sequence_length, loss_fun, random_seed):
282
+ MODEL_VERSION = f"SpliceAI_{project_name}_{flanking_size}_{exp_num}_rs{random_seed}"
283
+ model_train_outdir = f"{output_dir}/{MODEL_VERSION}/{exp_num}/"
284
+ model_output_base = f"{model_train_outdir}models/"
285
+ log_output_base = f"{model_train_outdir}LOG/"
286
+ log_output_train_base = f"{log_output_base}TRAIN/"
287
+ log_output_val_base = f"{log_output_base}VAL/"
288
+ log_output_test_base = f"{log_output_base}TEST/"
289
+ for path in [model_output_base, log_output_train_base, log_output_val_base, log_output_test_base]:
290
+ os.makedirs(path, exist_ok=True)
291
+ return model_output_base, log_output_train_base, log_output_val_base, log_output_test_base
292
+
293
+
294
+ def load_data_from_shard(h5f, shard_idx, device, batch_size, params, shuffle=False):
295
+ X = h5f[f'X{shard_idx}'][:].transpose(0, 2, 1)
296
+ Y = h5f[f'Y{shard_idx}'][0, ...].transpose(0, 2, 1)
297
+ X = torch.tensor(X, dtype=torch.float32)
298
+ Y = torch.tensor(Y, dtype=torch.float32)
299
+ ds = TensorDataset(X, Y)
300
+ return DataLoader(ds, batch_size=batch_size, shuffle=shuffle, drop_last=True, pin_memory=True)
301
+
302
+
303
+ def classwise_accuracy(true_classes, predicted_classes, num_classes):
304
+ class_accuracies = []
305
+ for i in range(num_classes):
306
+ true_positives = np.sum((predicted_classes == i) & (true_classes == i))
307
+ total_class_samples = np.sum(true_classes == i)
308
+ if total_class_samples > 0:
309
+ accuracy = true_positives / total_class_samples
310
+ else:
311
+ accuracy = 0.0
312
+ class_accuracies.append(accuracy)
313
+ return class_accuracies
314
+
315
+
316
+ def metrics(batch_ypred, batch_ylabel, metric_files, run_mode):
317
+ _, predicted_classes = torch.max(batch_ypred, 1)
318
+ true_classes = torch.argmax(batch_ylabel, dim=1)
319
+ true_classes = true_classes.numpy()
320
+ predicted_classes = predicted_classes.numpy()
321
+ true_classes_flat = true_classes.flatten()
322
+ predicted_classes_flat = predicted_classes.flatten()
323
+ accuracy = accuracy_score(true_classes_flat, predicted_classes_flat)
324
+ precision, recall, f1, _ = precision_recall_fscore_support(true_classes_flat, predicted_classes_flat, average=None)
325
+ class_accuracies = classwise_accuracy(true_classes, predicted_classes, 3)
326
+ overall_accuracy = np.mean(class_accuracies)
327
+ print(f"Overall Accuracy: {overall_accuracy}")
328
+ for k, v in metric_files.items():
329
+ with open(v, 'a') as f:
330
+ if k == "accuracy":
331
+ f.write(f"{overall_accuracy}\n")
332
+ ss_types = ["Non-splice", "acceptor", "donor"]
333
+ for i, (acc, prec, rec, f1_score) in enumerate(zip(class_accuracies, precision, recall, f1)):
334
+ print(f"Class {ss_types[i]}\t: Accuracy={acc}, Precision={prec}, Recall={rec}, F1={f1_score}")
335
+ if ss_types[i] == "Non-splice":
336
+ continue
337
+ for k, v in metric_files.items():
338
+ with open(v, 'a') as f:
339
+ if k == f"{ss_types[i]}_precision":
340
+ f.write(f"{prec}\n")
341
+ elif k == f"{ss_types[i]}_recall":
342
+ f.write(f"{rec}\n")
343
+ elif k == f"{ss_types[i]}_f1":
344
+ f.write(f"{f1_score}\n")
345
+ elif k == f"{ss_types[i]}_accuracy":
346
+ f.write(f"{acc}\n")
347
+
348
+
349
+ def model_evaluation(batch_ylabel, batch_ypred, metric_files, run_mode, criterion):
350
+ batch_ylabel = torch.cat(batch_ylabel, dim=0)
351
+ batch_ypred = torch.cat(batch_ypred, dim=0)
352
+ is_expr = (batch_ylabel.sum(axis=(1,2)) >= 1).cpu().numpy()
353
+ if np.any(is_expr):
354
+ subset_size = 1000
355
+ indices = np.arange(batch_ylabel[is_expr].shape[0])
356
+ subset_indices = np.random.choice(indices, size=min(subset_size, len(indices)), replace=False)
357
+ batch_ylabel = batch_ylabel[is_expr][subset_indices, :, :]
358
+ batch_ypred = batch_ypred[is_expr][subset_indices, :, :]
359
+ Y_true_1 = batch_ylabel[:, 1, :].flatten().cpu().detach().numpy()
360
+ Y_true_2 = batch_ylabel[:, 2, :].flatten().cpu().detach().numpy()
361
+ Y_pred_1 = batch_ypred[:, 1, :].flatten().cpu().detach().numpy()
362
+ Y_pred_2 = batch_ypred[:, 2, :].flatten().cpu().detach().numpy()
363
+ acceptor_topk_accuracy, acceptor_auprc = print_topl_statistics(np.asarray(Y_true_1),
364
+ np.asarray(Y_pred_1), metric_files["acceptor_topk_all"], ss_type='acceptor', print_top_k=True)
365
+ donor_topk_accuracy, donor_auprc = print_topl_statistics(np.asarray(Y_true_2),
366
+ np.asarray(Y_pred_2), metric_files["donor_topk_all"], ss_type='donor', print_top_k=True)
367
+ if criterion == "cross_entropy_loss":
368
+ loss = categorical_crossentropy_2d(batch_ylabel, batch_ypred)
369
+ elif criterion == "focal_loss":
370
+ loss = focal_loss(batch_ylabel, batch_ypred)
371
+ for k, v in metric_files.items():
372
+ with open(v, 'a') as f:
373
+ if k == "loss_batch":
374
+ f.write(f"{loss.item()}\n")
375
+ elif k == "donor_topk":
376
+ f.write(f"{donor_topk_accuracy}\n")
377
+ elif k == "donor_auprc":
378
+ f.write(f"{donor_auprc}\n")
379
+ elif k == "acceptor_topk":
380
+ f.write(f"{acceptor_topk_accuracy}\n")
381
+ elif k == "acceptor_auprc":
382
+ f.write(f"{acceptor_auprc}\n")
383
+ print("***************************************\n")
384
+ metrics(batch_ypred, batch_ylabel, metric_files, run_mode)
385
+ batch_ylabel = []
386
+ batch_ypred = []
387
+ return loss
388
+
389
+
390
+ def valid_epoch(model, h5f, idxs, batch_size, criterion, device, params, metric_files, flanking_size, run_mode):
391
+ print(f"\033[1m{run_mode.capitalize()}ing model...\033[0m")
392
+ model.eval()
393
+ running_loss = 0.0
394
+ np.random.seed(params["RANDOM_SEED"])
395
+ shuffled_idxs = np.random.choice(idxs, size=len(idxs), replace=False)
396
+ print("shuffled_idxs: ", shuffled_idxs)
397
+ batch_ylabel = []
398
+ batch_ypred = []
399
+ print_dict = {}
400
+ batch_idx = 0
401
+ for i, shard_idx in enumerate(shuffled_idxs, 1):
402
+ print(f"Shard {i}/{len(shuffled_idxs)}")
403
+ loader = load_data_from_shard(h5f, shard_idx, device, batch_size, params, shuffle=False)
404
+ pbar = tqdm(loader, leave=False, total=len(loader), desc=f'Shard {i}/{len(shuffled_idxs)}')
405
+ for batch in pbar:
406
+ DNAs, labels = batch[0].to(device), batch[1].to(device)
407
+ DNAs, labels = clip_datapoints(DNAs, labels, params["CL"], CL_max, params["N_GPUS"])
408
+ DNAs, labels = DNAs.to(torch.float32).to(device), labels.to(torch.float32).to(device)
409
+ yp = model(DNAs)
410
+ if criterion == "cross_entropy_loss":
411
+ loss = categorical_crossentropy_2d(labels, yp)
412
+ elif criterion == "focal_loss":
413
+ loss = focal_loss(labels, yp)
414
+ with open(metric_files["loss_every_update"], 'a') as f:
415
+ f.write(f"{loss.item()}\n")
416
+ running_loss += loss.item()
417
+ batch_ylabel.append(labels.detach().cpu())
418
+ batch_ypred.append(yp.detach().cpu())
419
+ print_dict["loss"] = loss.item()
420
+ pbar.set_postfix(print_dict)
421
+ pbar.update(1)
422
+ batch_idx += 1
423
+ pbar.close()
424
+ eval_loss = model_evaluation(batch_ylabel, batch_ypred, metric_files, run_mode, criterion)
425
+ return eval_loss
426
+
427
+
428
+ def train_epoch(model, h5f, idxs, batch_size, criterion, optimizer, scheduler, device, params, metric_files, flanking_size, run_mode, global_batch_idx):
429
+ print(f"\033[1m{run_mode.capitalize()}ing model...\033[0m")
430
+ model.train()
431
+ running_loss = 0.0
432
+ np.random.seed(params["RANDOM_SEED"])
433
+ shuffled_idxs = np.random.choice(idxs, size=len(idxs), replace=False)
434
+ print("shuffled_idxs: ", shuffled_idxs)
435
+ batch_ylabel = []
436
+ batch_ypred = []
437
+ print_dict = {}
438
+
439
+ # Calculate total number of batches in the epoch
440
+ total_batches_in_epoch = 0
441
+ for shard_idx in idxs:
442
+ # Load the loader to get its length
443
+ loader = load_data_from_shard(h5f, shard_idx, device, batch_size, params, shuffle=False)
444
+ total_batches_in_epoch += len(loader)
445
+
446
+ for i, shard_idx in enumerate(shuffled_idxs, 1):
447
+ print(f"Shard {i}/{len(shuffled_idxs)}")
448
+ loader = load_data_from_shard(h5f, shard_idx, device, batch_size, params, shuffle=True)
449
+ pbar = tqdm(loader, leave=False, total=len(loader), desc=f'Shard {i}/{len(shuffled_idxs)}')
450
+ for batch in pbar:
451
+ DNAs, labels = batch[0].to(device), batch[1].to(device)
452
+ DNAs, labels = clip_datapoints(DNAs, labels, params["CL"], CL_max, params["N_GPUS"])
453
+ DNAs, labels = DNAs.to(torch.float32).to(device), labels.to(torch.float32).to(device)
454
+ optimizer.zero_grad()
455
+ yp = model(DNAs)
456
+ if criterion == "cross_entropy_loss":
457
+ loss = categorical_crossentropy_2d(labels, yp)
458
+ elif criterion == "focal_loss":
459
+ loss = focal_loss(labels, yp)
460
+ with open(metric_files["loss_every_update"], 'a') as f:
461
+ f.write(f"{loss.item()}\n")
462
+ loss.backward()
463
+ optimizer.step()
464
+ running_loss += loss.item()
465
+ batch_ylabel.append(labels.detach().cpu())
466
+ batch_ypred.append(yp.detach().cpu())
467
+ print_dict["loss"] = loss.item()
468
+ pbar.set_postfix(print_dict)
469
+ pbar.update(1)
470
+
471
+ # Update the scheduler
472
+ epoch_fraction = global_batch_idx / total_batches_in_epoch
473
+ scheduler.step(epoch_fraction)
474
+ # Log current learning rate
475
+ current_lr = scheduler.get_last_lr()[0]
476
+ print_dict["lr"] = f"{current_lr:.6e}"
477
+ global_batch_idx += 1 # Increment global batch index
478
+ with open(metric_files['learning_rate_every_batch'], 'a') as f:
479
+ f.write(f"{current_lr}\n")
480
+ pbar.close()
481
+ eval_loss = model_evaluation(batch_ylabel, batch_ypred, metric_files, run_mode, criterion)
482
+ return eval_loss, global_batch_idx
483
+
484
+
485
+ def calculate_metrics(y_true, y_pred):
486
+ """Calculate metrics including precision, recall, f1-score, and accuracy."""
487
+ precision, recall, f1, _ = precision_recall_fscore_support(y_true, y_pred, average='binary', zero_division=0)
488
+ accuracy = accuracy_score(y_true, y_pred)
489
+ return precision, recall, f1, accuracy
490
+
491
+
492
+ def threshold_predictions(y_probs, threshold=0.5):
493
+ """Threshold probabilities to get binary predictions."""
494
+ return (y_probs > threshold).astype(int)
495
+
496
+
497
+ def clip_datapoints(X, Y, CL, CL_max, N_GPUS):
498
+ """
499
+ This function is necessary to make sure of the following:
500
+ (i) Each time model_m.fit is called, the number of datapoints is a
501
+ multiple of N_GPUS. Failure to ensure this often results in crashes.
502
+ (ii) If the required context length is less than CL_max, then
503
+ appropriate clipping is done below.
504
+ Additionally, Y is also converted to a list (the .h5 files store
505
+ them as an array).
506
+ """
507
+ rem = X.shape[0]%N_GPUS
508
+ clip = (CL_max-CL)//2
509
+ if rem != 0 and clip != 0:
510
+ return X[:-rem, :, clip:-clip], Y[:-rem]
511
+ elif rem == 0 and clip != 0:
512
+ return X[:, :, clip:-clip], Y
513
+ elif rem != 0 and clip == 0:
514
+ return X[:-rem], Y[:-rem]
515
+ else:
516
+ return X, Y
517
+
518
+
519
+ def print_topl_statistics(y_true, y_pred, file, ss_type='acceptor', print_top_k=False):
520
+ # Prints the following information: top-kL statistics for k=0.5,1,2,4,
521
+ # auprc, thresholds for k=0.5,1,2,4, number of true splice sites.
522
+ idx_true = np.nonzero(y_true == 1)[0]
523
+ argsorted_y_pred = np.argsort(y_pred)
524
+ sorted_y_pred = np.sort(y_pred)
525
+ topkl_accuracy = []
526
+ threshold = []
527
+ for top_length in [0.5, 1, 2, 4]:
528
+ num_elements = int(top_length * len(idx_true))
529
+ if num_elements > len(y_pred): # Check to prevent out-of-bounds access
530
+ print(f"Warning: Requested top_length {top_length} with {len(idx_true)} true elements exceeds y_pred size of {len(y_pred)}. Adjusting to fit.")
531
+ num_elements = len(y_pred) # Adjust num_elements to prevent out-of-bounds error
532
+ idx_pred = argsorted_y_pred[-int(top_length*len(idx_true)):]
533
+ topkl_accuracy += [np.size(np.intersect1d(idx_true, idx_pred)) \
534
+ / float(min(len(idx_pred), len(idx_true))+1e-10)]
535
+ threshold += [sorted_y_pred[-num_elements]]
536
+ auprc = average_precision_score(y_true, y_pred)
537
+ if print_top_k:
538
+ print(f"\n\033[1m{ss_type}:\033[0m")
539
+ print((("%.4f\t\033[91m%.4f\t\033[0m%.4f\t%.4f\t\033[94m%.4f\t\033[0m"
540
+ + "%.4f\t%.4f\t%.4f\t%.4f\t%d") % (topkl_accuracy[0], topkl_accuracy[1], topkl_accuracy[2],
541
+ topkl_accuracy[3], auprc, threshold[0], threshold[1],
542
+ threshold[2], threshold[3], len(idx_true))))
543
+ with open(file, 'a') as f:
544
+ f.write((("%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t"
545
+ + "%.4f\t%.4f\t%.4f\t%.4f\t%d\n") % (topkl_accuracy[0], topkl_accuracy[1], topkl_accuracy[2],
546
+ topkl_accuracy[3], auprc, threshold[0], threshold[1],
547
+ threshold[2], threshold[3], len(idx_true))))
548
+ return topkl_accuracy[1], auprc
549
+
550
+
551
+ def weighted_binary_cross_entropy(output, target, weights=None):
552
+ if weights is not None:
553
+ assert len(weights) == 2
554
+ loss = weights[1] * (target * torch.log(output+1e-10)) + \
555
+ weights[0] * ((1 - target) * torch.log(1 - output+1e-10))
556
+ else:
557
+ loss = target * torch.log(output+1e-10) + (1 - target) * torch.log(1 - output+1e-10)
558
+ return torch.neg(torch.mean(loss))
559
+
560
+
561
+ def categorical_crossentropy_2d(y_true, y_pred):
562
+ """
563
+ Compute 2D categorical cross-entropy loss.
564
+
565
+ Parameters:
566
+ - y_true: tensor of true labels.
567
+ - y_pred: tensor of predicted labels.
568
+
569
+ Returns:
570
+ - loss: computed categorical cross-entropy loss.
571
+ """
572
+ return - torch.mean(y_true[:, 0, :]*torch.log(y_pred[:, 0, :]+1e-10)
573
+ + y_true[:, 1, :]*torch.log(y_pred[:, 1, :]+1e-10)
574
+ + y_true[:, 2, :]*torch.log(y_pred[:, 2, :]+1e-10))
575
+
576
+
577
+ def focal_loss(y_true, y_pred, alpha=0.25, gamma=2.0):
578
+ """
579
+ Compute 2D focal loss.
580
+
581
+ Parameters:
582
+ - y_true: tensor of true labels.
583
+ - y_pred: tensor of predicted labels.
584
+ - gamma: focusing parameter.
585
+ - alpha: balancing factor.
586
+
587
+ Returns:
588
+ - loss: computed focal loss.
589
+ """
590
+ # Ensuring numerical stability
591
+ gamma = 2
592
+ epsilon = 1e-10
593
+ return - torch.mean(y_true[:, 0, :]*torch.log(y_pred[:, 0, :]+epsilon) * torch.pow(torch.sub(1, y_pred[:, 0, :]), gamma)
594
+ + y_true[:, 1, :]*torch.log(y_pred[:, 1, :]+epsilon) * torch.pow(torch.sub(1, y_pred[:, 1, :]), gamma)
595
+ + y_true[:, 2, :]*torch.log(y_pred[:, 2, :]+epsilon) * torch.pow(torch.sub(1, y_pred[:, 2, :]), gamma))
596
+
597
+
598
+ def train_model(model, optimizer, scheduler, train_h5f, test_h5f, train_idxs, val_idxs, test_idxs,
599
+ model_output_base, args, device, params,
600
+ train_metric_files, valid_metric_files, test_metric_files):
601
+ print("train_idxs: ", train_idxs)
602
+ print("val_idxs: ", val_idxs)
603
+ print("test_idxs: ", test_idxs)
604
+ best_val_loss = float('inf')
605
+ epochs_no_improve = 0
606
+ global_batch_idx = 0 # Initialize before the training loop
607
+ for epoch in range(args.epochs):
608
+ print(f"\n{'='*60}")
609
+ # current_lr = optimizer.param_groups[0]['lr']
610
+ # print(f">> Epoch {epoch + 1}; Current Learning Rate: {current_lr}")
611
+ start_time = time.time()
612
+ train_loss, global_batch_idx= train_epoch(model, train_h5f,
613
+ train_idxs, params["BATCH_SIZE"], args.loss, optimizer, scheduler, device, params, train_metric_files, args.flanking_size, run_mode="train", global_batch_idx=global_batch_idx)
614
+ val_loss = valid_epoch(model, train_h5f, val_idxs, params["BATCH_SIZE"], args.loss, device,
615
+ params, valid_metric_files, args.flanking_size, "validation")
616
+ test_loss = valid_epoch(model, test_h5f, test_idxs, params["BATCH_SIZE"], args.loss, device,
617
+ params, test_metric_files, args.flanking_size, "test")
618
+ print(f"Training Loss: {train_loss}")
619
+ print(f"Validation Loss: {val_loss}")
620
+ print(f"Testing Loss: {test_loss}")
621
+ torch.save(model.state_dict(), f"{model_output_base}/model_{epoch}.pt")
622
+ if args.early_stopping:
623
+ if val_loss.item() < best_val_loss:
624
+ best_val_loss = val_loss.item()
625
+ torch.save(model.state_dict(), f"{model_output_base}/model_best.pt")
626
+ print("New best model saved.")
627
+ epochs_no_improve = 0
628
+ else:
629
+ epochs_no_improve += 1
630
+ print(f"No improvement in validation loss for {epochs_no_improve} epochs.")
631
+ if epochs_no_improve >= args.patience:
632
+ print("Early stopping triggered.")
633
+ break
634
+ else:
635
+ if val_loss.item() < best_val_loss:
636
+ best_val_loss = val_loss.item()
637
+ torch.save(model.state_dict(), f"{model_output_base}/model_best.pt")
638
+ print("New best model saved.")
639
+ current_lr = scheduler.get_last_lr()[0]
640
+ with open(train_metric_files['learning_rate_every_epoch'], 'a') as f:
641
+ f.write(f"{current_lr}\n")
642
+ print(f">> Epoch {epoch + 1}; Final Learning Rate: {current_lr}")
643
+ print(f"--- {time.time() - start_time:.2f} seconds ---")
644
+ print("="*60)
File without changes