-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask2.py
More file actions
1385 lines (1131 loc) · 51.1 KB
/
Copy pathtask2.py
File metadata and controls
1385 lines (1131 loc) · 51.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import os.path
import random
import pickle
import hashlib
from pathlib import Path
import numpy as np
import pandas as pd
from typing import Dict, List
import torch
from torch.utils.data import Dataset
import tensorflow as tf
from transformers import AutoTokenizer, AutoModel
from torch import nn
from torch.utils.data import DataLoader
from sklearn.metrics import roc_auc_score, f1_score, recall_score, precision_score
import warnings
warnings.filterwarnings('ignore')
# Import matplotlib for plotting loss curves
try:
import matplotlib
matplotlib.use('Agg') # Use non-interactive backend, suitable for environments without GUI
import matplotlib.pyplot as plt
MATPLOTLIB_AVAILABLE = True
except ImportError:
MATPLOTLIB_AVAILABLE = False
print("matplotlib is not installed. Cannot plot loss curves. You can install it using pip install matplotlib.")
# Global cache manager
class CacheManager:
def __init__(self, cache_dir="dataset_cache"):
self.cache_dir = Path(cache_dir)
self.cache_dir.mkdir(exist_ok=True)
self.embedding_cache = {}
self.report_cache = {}
self.tokenized_cache = {}
self.max_memory_entries = 5000 # Memory cache maximum entries
self.stats = {"hit": 0, "miss": 0}
def _get_cache_path(self, key, prefix):
"""Get cache file path"""
# Use hash to ensure safe and unique file names
key_hash = hashlib.md5(key.encode()).hexdigest()
return self.cache_dir / f"{prefix}_{key_hash}.pkl"
def get_embedding(self, path):
"""Get embedding vector, prioritize from memory cache, then from disk cache, then load original file"""
if path in self.embedding_cache:
self.stats["hit"] += 1
return self.embedding_cache[path]
cache_path = self._get_cache_path(path, "embed")
if cache_path.exists():
try:
with open(cache_path, 'rb') as f:
embedding = pickle.load(f)
# Update memory cache
if len(self.embedding_cache) < self.max_memory_entries:
self.embedding_cache[path] = embedding
self.stats["hit"] += 1
return embedding
except Exception as e:
print(f"Error reading embedding cache: {e}")
# Cache miss, load original file
self.stats["miss"] += 1
embedding = load_embedding(path)
# Save to disk cache
try:
with open(cache_path, 'wb') as f:
pickle.dump(embedding, f)
# Update memory cache
if len(self.embedding_cache) < self.max_memory_entries:
self.embedding_cache[path] = embedding
except Exception as e:
print(f"Error saving embedding cache: {e}")
return embedding
def get_report(self, path):
"""Get report text, prioritize from memory cache, then from disk cache, then load original file"""
if path in self.report_cache:
self.stats["hit"] += 1
return self.report_cache[path]
cache_path = self._get_cache_path(path, "report")
if cache_path.exists():
try:
with open(cache_path, 'rb') as f:
report = pickle.load(f)
# Update memory cache
if len(self.report_cache) < self.max_memory_entries:
self.report_cache[path] = report
self.stats["hit"] += 1
return report
except Exception as e:
print(f"Error reading report cache: {e}")
# Cache miss, load original file
self.stats["miss"] += 1
try:
with open(path, 'r', encoding='utf-8') as f:
report = f.read()
# Save to disk cache
try:
with open(cache_path, 'wb') as f:
pickle.dump(report, f)
# Update memory cache
if len(self.report_cache) < self.max_memory_entries:
self.report_cache[path] = report
except Exception as e:
print(f"Error saving report cache: {e}")
return report
except Exception:
return None
def get_tokenized(self, text, tokenizer, max_length=512):
"""Get tokenized text, only use memory cache to avoid serialization issues"""
# Create a unique key containing text and tokenizer information
key = f"{tokenizer.__class__.__name__}_{max_length}_{hashlib.md5(text.encode()).hexdigest()}"
if key in self.tokenized_cache:
self.stats["hit"] += 1
return self.tokenized_cache[key]
# Cache miss, execute tokenization
self.stats["miss"] += 1
tokenized = tokenizer(
text,
padding="max_length",
truncation=True,
max_length=max_length,
return_tensors="pt"
)
# Update memory cache
if len(self.tokenized_cache) < self.max_memory_entries:
self.tokenized_cache[key] = tokenized
return tokenized
def clear_memory_cache(self):
"""Clear memory cache but keep disk cache"""
self.embedding_cache.clear()
self.report_cache.clear()
self.tokenized_cache.clear()
# def print_stats(self):
# """Print cache hit rate statistics"""
# total = self.stats["hit"] + self.stats["miss"]
# if total > 0:
# hit_rate = (self.stats["hit"] / total) * 100
# print(f"Cache hit rate: {hit_rate:.2f}% (hit: {self.stats['hit']}, miss: {self.stats['miss']})")
# else:
# print("Cache not used yet")
# Create global cache manager instance
cache_manager = CacheManager()
def load_embedding(embedding_path):
try:
# Suppress TensorFlow warnings
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
raw_dataset = tf.data.TFRecordDataset([embedding_path])
embedding_values = None
for raw_record in raw_dataset.take(1):
example = tf.train.Example()
example.ParseFromString(raw_record.numpy())
embedding_feature = example.features.feature['embedding']
embedding_values = embedding_feature.float_list.value
if embedding_values is None:
# Return a zero tensor if no embedding is found
return torch.zeros(1376, dtype=torch.float32)
return torch.tensor(embedding_values, dtype=torch.float32)
except Exception as e:
print(f"Error loading embedding from {embedding_path}: {e}")
# Return a zero tensor in case of error
return torch.zeros(1376, dtype=torch.float32)
####Define Dataset Class
##Here, a list is defined containing a series of diseases (pathologies), which are pathology labels in the dataset.
# These medical imaging labels are typically used for classification tasks (such as diagnosing whether an X-ray shows pneumonia, pleural effusion, etc.).
class MIMIC_Embed_Dataset(Dataset):
pathologies = [
"Enlarged Cardiomediastinum",
"Cardiomegaly",
"Lung Opacity",
"Lung Lesion",
"Edema",
"Consolidation",
"Pneumonia",
"Atelectasis",
"Pneumothorax",
"Pleural Effusion",
"Pleural Other",
"Fracture",
"Support Devices",
]
#80% training data (train)
#10% validation data (valid)
#10% test data (test)
split_ratio = [0.8, 0.1, 0.1]
def __init__(
self,
embedpath, # Root directory of embedding .tfrecord files
csvpath,
metacsvpath,
views=["PA"],
data_aug=None, # Data augmentation (not used currently)
seed=0, # Set random seed for reproducibility
unique_patients=True, # Whether to select only one image per patient (to reduce data correlation)
mode=["train", "valid", "test"][0],
):
super().__init__()
np.random.seed(seed) # Reset the seed so all runs are the same.
#Ensures NumPy-based randomness is reproducible.
self.pathologies = sorted(self.pathologies)
self.mode = mode
self.embedpath = embedpath
self.data_aug = data_aug
self.csvpath = csvpath
self.csv = pd.read_csv(self.csvpath)
self.metacsvpath = metacsvpath
self.metacsv = pd.read_csv(self.metacsvpath)
self.csv = self.csv.set_index(["subject_id", "study_id"])
self.metacsv = self.metacsv.set_index(["subject_id", "study_id"]) # First read the data, then update its index, logically written in two steps
self.csv = self.csv.join(self.metacsv).reset_index() # self.csv.join(self.metacsv) means merging (or "concatenating") the columns of self.metacsv into self.csv based on their common indices
# reset_index() converts the index back to regular columns and generates a new default integer index (0, 1, 2, ...), making it easier to index data by row number in subsequent operations
# Keep only the desired view
self.csv["view"] = self.csv["ViewPosition"]
self.limit_to_selected_views(views)
if unique_patients:
self.csv = self.csv.groupby("subject_id").first().reset_index() # Ensure only one record per patient
n_row = self.csv.shape[0] # Calculate total number of rows
# spit data to one of train valid test
if self.mode == "train":
self.csv = self.csv[: int(n_row * self.split_ratio[0])] # Take records from start to 0.8 * n_row as training set
elif self.mode == "valid":
self.csv = self.csv[
int(n_row * self.split_ratio[0]) : int(
n_row * (self.split_ratio[0] + self.split_ratio[1])
)
]
elif self.mode == "test":
self.csv = self.csv[-int(n_row * self.split_ratio[-1]) :]
else:
raise ValueError(
f"attr:mode has to be one of [train, valid, test] but your input is {self.mode}"
)
# Get our classes.
healthy = self.csv["No Finding"] == 1
labels = []
for pathology in self.pathologies:
if pathology in self.csv.columns:
self.csv.loc[healthy, pathology] = 0
mask = self.csv[pathology]
labels.append(mask.values) # Add this pathology's column data to the labels list
self.labels = np.asarray(labels).T # .T means transpose, so final self.labels is a matrix of shape (N_samples, 13)
self.labels = self.labels.astype(np.float32) # Convert label data to float32 type for easier model training and processing
# Make all the -1 values into nans to keep things simple
self.labels[self.labels == -1] = np.nan # Replace -1 with NaN so these can be ignored during training
# Rename pathologies
self.pathologies = list(
np.char.replace(self.pathologies, "Pleural Effusion", "Effusion")
)
# add consistent csv values
self.csv["offset_day_int"] = self.csv["StudyDate"] # offset_day_int directly copies the StudyDate field, possibly for later time analysis (e.g., sorting, grouping)
# patientid
self.csv["patientid"] = self.csv["subject_id"].astype(str) # patientid converts subject_id to string format for path concatenation or image file lookup
def string(self):
return self.__class__.__name__ + " num_samples={} views={}".format(
len(self), self.views,
)
def limit_to_selected_views(self, views):
"""This function is called by subclasses to filter the
images by view based on the values in .csv['view']
"""
if type(views) is not list:
views = [views]
if '*' in views:
# if you have the wildcard, the rest are irrelevant
views = ["*"]
self.views = views
# missing data is unknown
self.csv.view.fillna("UNKNOWN", inplace=True)
if "*" not in views:
self.csv = self.csv[self.csv["view"].isin(self.views)] # Select the view
def __len__(self):
return len(self.labels) # Returns the number of samples, which is the "length" of this dataset - i.e., the number of samples to train
def __getitem__(self, idx): # Returns a dictionary
sample = {}
sample["idx"] = idx
sample["lab"] = torch.tensor(self.labels[idx], dtype=torch.float32) # Convert to tensor
subjectid = str(self.csv.iloc[idx]["subject_id"]) # Extract patient-related ID from row idx of self.csv
studyid = str(self.csv.iloc[idx]["study_id"])
dicom_id = str(self.csv.iloc[idx]["dicom_id"])
#data_aug
embed_file = os.path.join(
self.embedpath,
"p" + subjectid[:2],
"p" + subjectid,
"s" + studyid,
dicom_id + ".tfrecord",
)
sample["embedding"] = cache_manager.get_embedding(embed_file)
#sample["embedding"] = embed_file
return sample
# {
# "idx": 5,
# "lab": tensor([0., 1., nan, ..., 0.]),
# "embedding": tensor([...]) # shape: (1376,) or whatever your embedding size is
# }
embedpath = "/home/lde/SPH6004/generalized-image-embeddings-for-the-mimic-chest-x-ray-dataset-1.0/files"
csvpath = "/home/lde/SPH6004/mimic-cxr-2.0.0-chexpert.csv"
metacsvpath = "/home/lde/SPH6004/mimic-cxr-2.0.0-metadata.csv"
# Extended Dataset class that includes reports
class MIMIC_LLM_Dataset(MIMIC_Embed_Dataset):
def __init__(
self,
embedpath,
csvpath,
metacsvpath,
reportpath,
tokenizer,
max_report_length=512,
views=["PA"],
data_aug=None,
seed=0,
unique_patients=True,
mode=["train", "valid", "test"][0],
):
super().__init__(
embedpath=embedpath,
csvpath=csvpath,
metacsvpath=metacsvpath,
views=views,
data_aug=data_aug,
seed=seed,
unique_patients=unique_patients,
mode=mode,
)
self.reportpath = reportpath
self.tokenizer = tokenizer
self.max_report_length = max_report_length
self.prompt = "analyze this report"
def _load_report(self, subjectid, studyid):
"""Load a report file for a given subject and study ID using cache manager"""
# Create the report file path
report_file = os.path.join(
self.reportpath,
"p" + subjectid[:2],
"p" + subjectid,
f"s{studyid}.txt"
)
# Default report text if not found
default_report = self.prompt + ": [No report available]"
# Check if file exists before trying to open it
if not os.path.exists(report_file):
return default_report
# Use cache manager to get the report
report_text = cache_manager.get_report(report_file)
# If report couldn't be loaded or is empty
if not report_text or len(report_text) < 5:
return default_report
# Add the prompt to the beginning of the report
return f"{self.prompt}: {report_text}"
def __getitem__(self, idx):
# Get the basic sample from the parent class
try:
sample = super().__getitem__(idx)
# Add report text
subjectid = str(self.csv.iloc[idx]["subject_id"])
studyid = str(self.csv.iloc[idx]["study_id"])
report_text = self._load_report(subjectid, studyid)
sample["report_text"] = report_text
return sample
except Exception as e:
print(f"Error in __getitem__ for idx {idx}: {e}")
# Return a fallback sample with dummy data
return {
"idx": idx,
"lab": torch.zeros(len(self.pathologies), dtype=torch.float32),
"embedding": torch.zeros(1376, dtype=torch.float32),
"report_text": self.prompt + ": [Error loading data]"
}
# MLP for processing embeddings
class MLPProcessor(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, dropout=0.2):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, output_dim),
nn.BatchNorm1d(output_dim),
nn.ReLU(),
nn.Dropout(dropout)
)
def forward(self, x):
return self.layers(x)
# Classification head for the LLM output
class ClassificationHead(nn.Module):
def __init__(self, input_dim, hidden_dim, num_classes, dropout=0.2):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, num_classes)
# Removed Sigmoid - will be included in BCEWithLogitsLoss
)
def forward(self, x):
return self.layers(x)
# Full model combining LLM, MLP, and classification
class LLMChestXRayClassifier(nn.Module):
def __init__(
self,
llm_model_name,
embedding_dim,
mlp_hidden_dim=256,
mlp_output_dim=768,
classifier_hidden_dim=256,
num_classes=13,
freeze_llm=True
):
super().__init__()
# Initialize LLM
self.llm = AutoModel.from_pretrained(llm_model_name)
self.llm_model_name = llm_model_name
# Freeze LLM parameters to save memory and speed up training
if freeze_llm:
for param in self.llm.parameters():
param.requires_grad = False
# MLP for processing image embeddings
self.mlp = MLPProcessor(
input_dim=embedding_dim,
hidden_dim=mlp_hidden_dim,
output_dim=mlp_output_dim
)
# Get the correct hidden size based on the model
hidden_size = self.llm.config.hidden_size
# Add projection layer for combining image and text features
self.projection = nn.Linear(mlp_output_dim + hidden_size, hidden_size)
# Classification head
self.classifier = ClassificationHead(
input_dim=hidden_size, # Size of the LLM's output
hidden_dim=classifier_hidden_dim,
num_classes=num_classes
)
# Add input normalization
self.input_norm = nn.LayerNorm(embedding_dim)
def forward(self, image_embeddings, input_ids, attention_mask):
"""
Forward pass through the model
Args:
image_embeddings: Tensor of shape (batch_size, embedding_dim)
input_ids: Tokenized report text, shape (batch_size, seq_length)
attention_mask: Attention mask for the report text, shape (batch_size, seq_length)
Returns:
Tensor of shape (batch_size, num_classes) with logits
"""
# Normalize image embeddings
image_embeddings = self.input_norm(image_embeddings)
# Process image embeddings through MLP
processed_img_embed = self.mlp(image_embeddings)
# Get LLM embeddings for the text
llm_outputs = self.llm(
input_ids=input_ids,
attention_mask=attention_mask,
return_dict=True
)
# Extract the last hidden states
last_hidden_states = llm_outputs.last_hidden_state # (batch_size, seq_length, hidden_size)
# Extract the CLS token from the LLM output (first token)
text_cls_token = last_hidden_states[:, 0, :]
# Combine image and text representations by concatenation
combined_representation = torch.cat([processed_img_embed, text_cls_token], dim=1)
# Project the combined representation to the expected input size of the classifier
combined_cls = self.projection(combined_representation)
# Pass through classification head
logits = self.classifier(combined_cls)
return logits
# Collate function for the DataLoader
def collate_fn(batch):
"""
Custom collate function to prepare batches for the model
"""
# Extract components and create lists
idxs = [item["idx"] for item in batch]
# Ensure labels are tensors
labels = []
for item in batch:
if isinstance(item["lab"], torch.Tensor):
labels.append(item["lab"])
else:
labels.append(torch.tensor(item["lab"], dtype=torch.float32))
# Ensure embeddings are tensors
embeddings = []
for item in batch:
if isinstance(item["embedding"], torch.Tensor):
embeddings.append(item["embedding"])
else:
embeddings.append(torch.tensor(item["embedding"], dtype=torch.float32))
texts = [item["report_text"] for item in batch]
# Stack tensors
labels = torch.stack(labels)
embeddings = torch.stack(embeddings)
# Return as a dictionary
return {
"idxs": torch.tensor(idxs),
"labels": labels,
"embeddings": embeddings,
"texts": texts
}
# Training function
def train_model(model, tokenizer, train_loader, val_loader, device, epochs=5, lr=2e-5):
"""
Train the LLM model
Args:
model: The LLM model
tokenizer: Tokenizer for text processing
train_loader: DataLoader for training data
val_loader: DataLoader for validation data
device: Device to train on (cuda/cpu)
epochs: Number of epochs to train for
lr: Learning rate
Returns:
Trained model
"""
# Move model to device
model = model.to(device)
# Define optimizer and loss function
optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
criterion = nn.BCEWithLogitsLoss() # Changed from BCELoss to BCEWithLogitsLoss
best_val_loss = float('inf')
# Store loss values for plotting
train_losses = []
val_losses = []
epoch_train_losses = []
epoch_val_losses = []
print("\nStarting model training:")
print("=" * 60)
# Print cache usage
# print("\nInitial cache status:")
# cache_manager.print_stats()
for epoch in range(epochs):
model.train()
train_loss = 0
batch_losses = []
# Create progress bar for training
print(f"\nEpoch {epoch+1}/{epochs}")
print("-" * 60)
print("Training Progress:")
# Training loop
for i, batch in enumerate(train_loader):
# Move batch to device
embeddings = batch["embeddings"].to(device)
labels = batch["labels"].to(device)
texts = batch["texts"]
# Use cache manager to process text tokenization
# Tokenize texts in batches to save memory
encoded_texts_list = []
for text in texts:
# Use cache manager to get tokenized text
encoded_text = cache_manager.get_tokenized(text, tokenizer, max_length=512)
encoded_texts_list.append(encoded_text)
# Merge encoded texts into batches
input_ids = torch.cat([encoded_text.input_ids for encoded_text in encoded_texts_list], dim=0).to(device)
attention_mask = torch.cat([encoded_text.attention_mask for encoded_text in encoded_texts_list], dim=0).to(device)
# Zero gradients
optimizer.zero_grad()
# Forward pass
outputs = model(
image_embeddings=embeddings,
input_ids=input_ids,
attention_mask=attention_mask
)
# Handle NaN values in labels
mask = ~torch.isnan(labels)
filtered_outputs = outputs[mask]
filtered_labels = labels[mask]
# Calculate loss
if filtered_outputs.numel() > 0:
loss = criterion(filtered_outputs, filtered_labels)
else:
# Skip this batch if all values are NaN
print("Warning: All labels in current batch are NaN, skipping this batch")
continue
# Backward pass and optimization
loss.backward()
optimizer.step()
# Record loss
loss_value = loss.item()
train_loss += loss_value
batch_losses.append(loss_value)
# Print progress
if (i + 1) % max(1, len(train_loader) // 10) == 0:
progress = (i + 1) / len(train_loader) * 100
progress_bar = "=" * int(progress // 2) + ">" + " " * (50 - int(progress // 2))
print(f"[{progress_bar}] {progress:.1f}% - Batch {i+1}/{len(train_loader)}, Loss: {loss_value:.4f}")
# Calculate average training loss for this epoch
avg_train_loss = train_loss / len(train_loader)
epoch_train_losses.append(avg_train_loss)
# Validation
model.eval()
val_loss = 0
batch_val_losses = []
print("\nValidation Progress:")
with torch.no_grad():
for i, batch in enumerate(val_loader):
# Move batch to device
embeddings = batch["embeddings"].to(device)
labels = batch["labels"].to(device)
texts = batch["texts"]
# Use cache manager to process text tokenization
encoded_texts_list = []
for text in texts:
# Use cache manager to get tokenized text
encoded_text = cache_manager.get_tokenized(text, tokenizer, max_length=512)
encoded_texts_list.append(encoded_text)
# Merge encoded texts into batches
input_ids = torch.cat([encoded_text.input_ids for encoded_text in encoded_texts_list], dim=0).to(device)
attention_mask = torch.cat([encoded_text.attention_mask for encoded_text in encoded_texts_list], dim=0).to(device)
# Forward pass
outputs = model(
image_embeddings=embeddings,
input_ids=input_ids,
attention_mask=attention_mask
)
# Handle NaN values in labels
mask = ~torch.isnan(labels)
filtered_outputs = outputs[mask]
filtered_labels = labels[mask]
# Calculate loss
if filtered_outputs.numel() > 0:
loss = criterion(filtered_outputs, filtered_labels)
else:
# Skip this batch if all values are NaN
print("Warning: All labels in current batch are NaN, skipping this batch")
continue
loss_value = loss.item()
val_loss += loss_value
batch_val_losses.append(loss_value)
# Print progress
if (i + 1) % max(1, len(val_loader) // 5) == 0:
progress = (i + 1) / len(val_loader) * 100
progress_bar = "=" * int(progress // 2) + ">" + " " * (50 - int(progress // 2))
print(f"[{progress_bar}] {progress:.1f}% - Batch {i+1}/{len(val_loader)}, Loss: {loss_value:.4f}")
# Calculate average validation loss for this epoch
avg_val_loss = val_loss / len(val_loader)
epoch_val_losses.append(avg_val_loss)
# Print epoch summary
print("\n" + "=" * 60)
print(f"Epoch {epoch+1}/{epochs} Results:")
print(f"Training Loss: {avg_train_loss:.4f}")
print(f"Validation Loss: {avg_val_loss:.4f}")
# Store all batch losses for this epoch
train_losses.extend(batch_losses)
val_losses.extend(batch_val_losses)
# Save best model
if avg_val_loss < best_val_loss:
best_val_loss = avg_val_loss
torch.save(model.state_dict(), "best_model.pt")
print(f"*** Model saved! Current best validation loss: {best_val_loss:.4f} ***")
print("=" * 60)
# Print final summary
print("\nTraining completed!")
print("=" * 60)
print("Average loss per epoch:")
for epoch, (train_loss, val_loss) in enumerate(zip(epoch_train_losses, epoch_val_losses)):
print(f"Epoch {epoch+1}: Training Loss = {train_loss:.4f}, Validation Loss = {val_loss:.4f}")
print("=" * 60)
# Final cache statistics
# print("\nFinal cache usage:")
# cache_manager.print_stats()
# Try to plot losses if matplotlib is available
if MATPLOTLIB_AVAILABLE:
try:
# Plot epoch losses
plt.figure(figsize=(10, 5))
plt.plot(range(1, epochs+1), epoch_train_losses, 'b-', label='Training Loss')
plt.plot(range(1, epochs+1), epoch_val_losses, 'r-', label='Validation Loss')
plt.title('Loss per Epoch')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.grid(True)
plt.savefig('epoch_losses.png')
print("Loss curves saved to 'epoch_losses.png'")
# Plot all batch losses
plt.figure(figsize=(12, 6))
plt.plot(train_losses, 'b-', alpha=0.5, label='Batch Training Loss')
plt.plot([len(train_loader)*i for i in range(epochs)], epoch_train_losses, 'bo-', label='Average Training Loss per Epoch')
plt.title('Loss Changes During Training')
plt.xlabel('Batch')
plt.ylabel('Loss')
plt.legend()
plt.grid(True)
plt.savefig('batch_losses.png')
print("Batch loss curves saved to 'batch_losses.png'")
except Exception as e:
print(f"Error plotting loss curves: {e}")
return model
# Evaluation function
def evaluate_model(model, tokenizer, test_loader, device, pathologies=None):
"""
Evaluate the model on test data
Args:
model: The trained model
tokenizer: Tokenizer for text processing
test_loader: DataLoader for test data
device: Device to evaluate on (cuda/cpu)
pathologies: List of pathology names
Returns:
Dictionary of evaluation metrics
"""
model.eval()
# Get pathologies if not provided
if pathologies is None and hasattr(test_loader.dataset, 'pathologies'):
pathologies = test_loader.dataset.pathologies
all_preds = []
all_labels = []
print("Testing Progress:")
with torch.no_grad():
for i, batch in enumerate(test_loader):
# Move batch to device
embeddings = batch["embeddings"].to(device)
labels = batch["labels"].to(device)
texts = batch["texts"]
# Use cache manager to process text tokenization
encoded_texts_list = []
for text in texts:
# Use cache manager to get tokenized text
encoded_text = cache_manager.get_tokenized(text, tokenizer, max_length=512)
encoded_texts_list.append(encoded_text)
# Merge encoded texts into batches
input_ids = torch.cat([encoded_text.input_ids for encoded_text in encoded_texts_list], dim=0).to(device)
attention_mask = torch.cat([encoded_text.attention_mask for encoded_text in encoded_texts_list], dim=0).to(device)
# Forward pass
outputs = model(
image_embeddings=embeddings,
input_ids=input_ids,
attention_mask=attention_mask
)
# Apply sigmoid to convert logits to probabilities
outputs = torch.sigmoid(outputs)
# Store predictions and labels
all_preds.append(outputs.cpu().numpy())
all_labels.append(labels.cpu().numpy())
# Print progress
if (i + 1) % max(1, len(test_loader) // 5) == 0:
progress = (i + 1) / len(test_loader) * 100
progress_bar = "=" * int(progress // 2) + ">" + " " * (50 - int(progress // 2))
print(f"[{progress_bar}] {progress:.1f}% - Batch {i+1}/{len(test_loader)}")
# Concatenate predictions and labels
if all_preds and all_labels:
all_preds = np.concatenate(all_preds, axis=0)
all_labels = np.concatenate(all_labels, axis=0)
else:
print("Warning: No evaluable predictions or labels")
return {"auc": 0, "f1_score": 0, "recall": 0, "precision": 0}
print("\nCalculating evaluation metrics...")
# Calculate metrics
metrics = {}
# Handle NaN values
valid_indices = ~np.isnan(all_labels)
# Find optimal thresholds for each class
optimal_thresholds = []
print("\nCalculating optimal thresholds for each class:")
print("-" * 80)
print(f"{'Class Name':<30} {'Optimal Threshold':<10} {'Positive Ratio':<10} {'F1(0.5 Threshold)':<15} {'F1(Optimal Threshold)':<15}")
print("-" * 80)
# Per-class metrics with optimal thresholds
class_metrics = []
from sklearn.metrics import precision_recall_curve
for i in range(all_labels.shape[1]):
class_result = {}
mask = valid_indices[:, i]
if mask.sum() > 1:
y_true = all_labels[mask, i]
y_pred = all_preds[mask, i]
# Calculate class imbalance ratio
pos_ratio = np.sum(y_true) / len(y_true) if len(y_true) > 0 else 0
# Calculate F1 score with default threshold
y_pred_binary_default = (y_pred > 0.5).astype(int)
try:
f1_default = f1_score(y_true, y_pred_binary_default)
except:
f1_default = 0
# Only calculate AUC if we have both classes
if len(np.unique(y_true)) > 1:
try:
class_result['auc'] = roc_auc_score(y_true, y_pred)
except Exception as e:
class_result['auc'] = 0
print(f"Cannot calculate AUC for class {i}: {e}")
else:
class_result['auc'] = 0
# Only find optimal threshold if we have positive samples
if np.sum(y_true) > 0:
try:
# Find optimal threshold using precision-recall curve
precision, recall, thresholds = precision_recall_curve(y_true, y_pred)
# Calculate F1 score for each threshold
f1_scores = []
for p, r in zip(precision[:-1], recall[:-1]): # Last point has no threshold
if p + r > 0: # Avoid division by zero
f1 = 2 * p * r / (p + r)
else:
f1 = 0
f1_scores.append(f1)
# Use threshold that gives best F1 score
if f1_scores and thresholds.size > 0:
best_idx = np.argmax(f1_scores)
optimal_threshold = thresholds[best_idx]
best_f1 = f1_scores[best_idx]
else:
# Fallback if we can't compute optimal threshold
optimal_threshold = 0.5
best_f1 = f1_default
# Try different threshold if very small positive ratio
# if pos_ratio < 0.05 and optimal_threshold > 0.3:
# # For very imbalanced classes, try a lower threshold
# alternative_threshold = 0.1
# y_pred_binary_alt = (y_pred > alternative_threshold).astype(int)
# f1_alt = f1_score(y_true, y_pred_binary_alt)