123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155 |
- from model import ModelCT
- import os
- import numpy as np
- import torch
- from torch.utils.data import DataLoader
- from datareader import DataReader
- from sklearn.metrics import roc_auc_score
- import time
- main_path_to_data = "/data/PSUF_naloge/5-naloga/processed/"
- files_mild = os.listdir(os.path.join(main_path_to_data, "mild"))
- files_severe = os.listdir(os.path.join(main_path_to_data, "severe"))
- patients_mild = {file.split("_slice_")[0] for file in files_mild}
- patients_severe = {file.split("_slice_")[0] for file in files_severe}
- all_central_slices = (
- [("mild/" + patient_ID + "_slice_4.npy", 0) for patient_ID in patients_mild] +
- [("severe/" + patient_ID + "_slice_4.npy", 1) for patient_ID in patients_severe]
- )
- np.random.seed(42)
- np.random.shuffle(all_central_slices)
- total_samples = len(all_central_slices)
- train_info = all_central_slices[: int(0.6 * total_samples)]
- valid_info = all_central_slices[int(0.6 * total_samples) : int(0.8 * total_samples)]
- test_info = all_central_slices[int(0.8 * total_samples) :]
- model = ModelCT()
-
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
- learning_rate = 0.2e-3
- weight_decay = 0.0001
- total_epoch = 10
- train_dataset = DataReader(main_path_to_data, train_info)
- valid_dataset = DataReader(main_path_to_data, valid_info)
- train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True,)
- valid_loader = DataLoader(valid_dataset, batch_size=10, shuffle=False)
- model.to(device)
- criterion = torch.nn.BCEWithLogitsLoss()
- optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
- if __name__ == '__main__':
-
-
- best_auc = -np.inf
-
- for epoch in range(total_epoch):
- start_time = time.time()
- print(f"Epoch: {epoch + 1}/{total_epoch}")
-
- running_loss = 0.0
-
-
- model.train()
-
-
- for x, y in train_loader:
-
- x, y = x.to(device), y.to(device)
-
-
- optimizer.zero_grad()
-
-
- y_hat = model(x)
- loss = criterion(y_hat, y)
-
-
- loss.backward()
-
-
- optimizer.step()
-
-
- running_loss += loss.item()
-
-
- avg_loss = running_loss / len(train_loader)
-
-
-
-
-
- predictions = []
- trues = []
-
-
- model.eval()
- with torch.no_grad():
-
- for x, y in valid_loader:
-
- x, y = x.to(device), y.to(device)
-
-
- y_hat = model(x)
-
-
- probs = torch.sigmoid(y_hat)
-
-
- predictions.extend(probs.cpu().numpy().flatten().tolist())
- trues.extend(y.cpu().numpy().flatten().tolist())
-
-
- auc = roc_auc_score(trues, predictions)
-
- elapsed_time = time.time() - start_time
- print(f"AUC: {auc:.4f}, Avg Loss: {avg_loss:.4f}, Time: {elapsed_time:.2f} sec")
-
-
- if auc > best_auc:
- best_model_path = os.path.join("trained_models/", 'trained_model_weights.pth')
- torch.save(model.state_dict(), best_model_path)
- best_auc = auc
|