Delete utils.py
Browse files
utils.py
DELETED
|
@@ -1,223 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Module: utils.py
|
| 3 |
-
Description:
|
| 4 |
-
This module provides utility functions for the MODDA framework including:
|
| 5 |
-
- Evaluation metric calculation (ROC, AUPR, Accuracy, F1, etc.)
|
| 6 |
-
- Setting random seeds for reproducibility.
|
| 7 |
-
- Early stopping mechanism during training.
|
| 8 |
-
- Plotting ROC and Precision-Recall curves.
|
| 9 |
-
"""
|
| 10 |
-
|
| 11 |
-
import datetime
|
| 12 |
-
import numpy as np
|
| 13 |
-
import torch
|
| 14 |
-
import random
|
| 15 |
-
# import seaborn
|
| 16 |
-
import os
|
| 17 |
-
from sklearn.metrics import roc_curve, roc_auc_score, precision_recall_curve, average_precision_score
|
| 18 |
-
import matplotlib.pyplot as plt
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
def get_metrics_auc(real_score, predict_score):
|
| 22 |
-
"""
|
| 23 |
-
Compute the Area Under the ROC Curve (AUC) and the Average Precision (AUPR).
|
| 24 |
-
|
| 25 |
-
Parameters:
|
| 26 |
-
real_score (array-like): True binary labels.
|
| 27 |
-
predict_score (array-like): Predicted scores.
|
| 28 |
-
|
| 29 |
-
Returns:
|
| 30 |
-
tuple: (AUC, AUPR)
|
| 31 |
-
"""
|
| 32 |
-
auc = roc_auc_score(real_score, predict_score)
|
| 33 |
-
aupr = average_precision_score(real_score, predict_score)
|
| 34 |
-
return auc, aupr
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def get_metrics(real_score, predict_score):
|
| 38 |
-
"""
|
| 39 |
-
Calculate various performance metrics including AUC, AUPR, Accuracy, F1-Score, Precision, Recall, and Specificity.
|
| 40 |
-
|
| 41 |
-
The implementation is based on the method described in:
|
| 42 |
-
Yu Z, Huang F, Zhao X et al. Predicting drug-disease associations through layer attention graph convolutional network,
|
| 43 |
-
Brief Bioinform 2021;22.
|
| 44 |
-
|
| 45 |
-
Parameters:
|
| 46 |
-
real_score (array-like): True labels.
|
| 47 |
-
predict_score (array-like): Predicted scores.
|
| 48 |
-
|
| 49 |
-
Returns:
|
| 50 |
-
tuple: (AUC, AUPR, Accuracy, F1-Score, Precision, Recall, Specificity)
|
| 51 |
-
"""
|
| 52 |
-
# Obtain sorted unique predicted scores to generate thresholds
|
| 53 |
-
sorted_predict_score = np.array(sorted(list(set(np.array(predict_score).flatten()))))
|
| 54 |
-
sorted_predict_score_num = len(sorted_predict_score)
|
| 55 |
-
thresholds = sorted_predict_score[np.int32(sorted_predict_score_num * np.arange(1, 1000) / 1000)]
|
| 56 |
-
thresholds = np.asmatrix(thresholds)
|
| 57 |
-
thresholds_num = thresholds.shape[1]
|
| 58 |
-
|
| 59 |
-
# Create a prediction matrix for all thresholds
|
| 60 |
-
predict_score_matrix = np.tile(predict_score, (thresholds_num, 1))
|
| 61 |
-
negative_index = np.where(predict_score_matrix < thresholds.T)
|
| 62 |
-
positive_index = np.where(predict_score_matrix >= thresholds.T)
|
| 63 |
-
predict_score_matrix[negative_index] = 0
|
| 64 |
-
predict_score_matrix[positive_index] = 1
|
| 65 |
-
|
| 66 |
-
# Calculate TP, FP, FN, and TN for each threshold
|
| 67 |
-
TP = predict_score_matrix.dot(real_score.T)
|
| 68 |
-
FP = predict_score_matrix.sum(axis=1) - TP
|
| 69 |
-
FN = real_score.sum() - TP
|
| 70 |
-
TN = len(real_score.T) - TP - FP - FN
|
| 71 |
-
|
| 72 |
-
fpr = FP / (FP + TN)
|
| 73 |
-
tpr = TP / (TP + FN)
|
| 74 |
-
ROC_dot_matrix = np.mat(sorted(np.column_stack((fpr, tpr)).tolist())).T
|
| 75 |
-
ROC_dot_matrix.T[0] = [0, 0]
|
| 76 |
-
ROC_dot_matrix = np.c_[ROC_dot_matrix, [1, 1]]
|
| 77 |
-
x_ROC = ROC_dot_matrix[0].T
|
| 78 |
-
y_ROC = ROC_dot_matrix[1].T
|
| 79 |
-
auc = 0.5 * (x_ROC[1:] - x_ROC[:-1]).T * (y_ROC[:-1] + y_ROC[1:])
|
| 80 |
-
|
| 81 |
-
recall_list = tpr
|
| 82 |
-
precision_list = TP / (TP + FP)
|
| 83 |
-
PR_dot_matrix = np.mat(sorted(np.column_stack((recall_list, precision_list)).tolist())).T
|
| 84 |
-
PR_dot_matrix.T[0] = [0, 1]
|
| 85 |
-
PR_dot_matrix = np.c_[PR_dot_matrix, [1, 0]]
|
| 86 |
-
x_PR = PR_dot_matrix[0].T
|
| 87 |
-
y_PR = PR_dot_matrix[1].T
|
| 88 |
-
aupr = 0.5 * (x_PR[1:] - x_PR[:-1]).T * (y_PR[:-1] + y_PR[1:])
|
| 89 |
-
|
| 90 |
-
f1_score_list = 2 * TP / (len(real_score.T) + TP - TN)
|
| 91 |
-
accuracy_list = (TP + TN) / len(real_score.T)
|
| 92 |
-
specificity_list = TN / (TN + FP)
|
| 93 |
-
|
| 94 |
-
max_index = np.argmax(f1_score_list)
|
| 95 |
-
f1_score = f1_score_list[max_index]
|
| 96 |
-
accuracy = accuracy_list[max_index]
|
| 97 |
-
specificity = specificity_list[max_index]
|
| 98 |
-
recall = recall_list[max_index]
|
| 99 |
-
precision = precision_list[max_index]
|
| 100 |
-
return auc[0, 0], aupr[0, 0], accuracy, f1_score, precision, recall, specificity
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
def set_seed(seed=0):
|
| 104 |
-
"""
|
| 105 |
-
Set the random seed for Python, NumPy, and PyTorch for reproducibility.
|
| 106 |
-
|
| 107 |
-
Parameters:
|
| 108 |
-
seed (int): The random seed to set.
|
| 109 |
-
"""
|
| 110 |
-
random.seed(seed)
|
| 111 |
-
np.random.seed(seed)
|
| 112 |
-
torch.manual_seed(seed)
|
| 113 |
-
if torch.cuda.is_available():
|
| 114 |
-
torch.cuda.manual_seed(seed)
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
class EarlyStopping(object):
|
| 118 |
-
"""
|
| 119 |
-
Early stopping utility to halt training when the validation performance stops improving.
|
| 120 |
-
"""
|
| 121 |
-
|
| 122 |
-
def __init__(self, patience=10, saved_path="."):
|
| 123 |
-
"""
|
| 124 |
-
Parameters:
|
| 125 |
-
patience (int): Number of epochs with no improvement after which training is stopped.
|
| 126 |
-
saved_path (str): Directory path to save the model checkpoint.
|
| 127 |
-
"""
|
| 128 |
-
dt = datetime.datetime.now()
|
| 129 |
-
self.filename = os.path.join(
|
| 130 |
-
saved_path, "early_stop_{}_{}-{}-{}.pth".format(dt.date(), dt.hour, dt.minute, dt.second)
|
| 131 |
-
)
|
| 132 |
-
self.patience = patience
|
| 133 |
-
self.counter = 0
|
| 134 |
-
self.best_acc = None
|
| 135 |
-
self.best_loss = None
|
| 136 |
-
self.early_stop = False
|
| 137 |
-
|
| 138 |
-
def step(self, loss, acc, model):
|
| 139 |
-
"""
|
| 140 |
-
Check if early stopping condition is met based on current loss and accuracy.
|
| 141 |
-
|
| 142 |
-
Parameters:
|
| 143 |
-
loss (float): Current loss value.
|
| 144 |
-
acc (float): Current accuracy value.
|
| 145 |
-
model (torch.nn.Module): The model being trained.
|
| 146 |
-
|
| 147 |
-
Returns:
|
| 148 |
-
bool: True if early stopping condition is met, otherwise False.
|
| 149 |
-
"""
|
| 150 |
-
if self.best_loss is None:
|
| 151 |
-
self.best_acc = acc
|
| 152 |
-
self.best_loss = loss
|
| 153 |
-
self.save_checkpoint(model)
|
| 154 |
-
elif (loss > self.best_loss) and (acc < self.best_acc):
|
| 155 |
-
self.counter += 1
|
| 156 |
-
# Uncomment the following line for debugging
|
| 157 |
-
# print(f"EarlyStopping counter: {self.counter} out of {self.patience}")
|
| 158 |
-
if self.counter >= self.patience:
|
| 159 |
-
self.early_stop = True
|
| 160 |
-
else:
|
| 161 |
-
if (loss <= self.best_loss) and (acc >= self.best_acc):
|
| 162 |
-
self.save_checkpoint(model)
|
| 163 |
-
self.best_loss = np.min((loss, self.best_loss))
|
| 164 |
-
self.best_acc = np.max((acc, self.best_acc))
|
| 165 |
-
self.counter = 0
|
| 166 |
-
return self.early_stop
|
| 167 |
-
|
| 168 |
-
def save_checkpoint(self, model):
|
| 169 |
-
"""Save the current model state as a checkpoint."""
|
| 170 |
-
torch.save(model.state_dict(), self.filename)
|
| 171 |
-
|
| 172 |
-
def load_checkpoint(self, model):
|
| 173 |
-
"""Load the best model checkpoint."""
|
| 174 |
-
model.load_state_dict(torch.load(self.filename))
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
def plot_result_auc(args, label, predict, auc):
|
| 178 |
-
"""
|
| 179 |
-
Plot and save the Receiver Operating Characteristic (ROC) curve.
|
| 180 |
-
|
| 181 |
-
Parameters:
|
| 182 |
-
args: Argument object containing saved_path.
|
| 183 |
-
label (array-like): True labels.
|
| 184 |
-
predict (array-like): Predicted scores.
|
| 185 |
-
auc (float): Computed AUC value.
|
| 186 |
-
"""
|
| 187 |
-
# seaborn.set_style()
|
| 188 |
-
fpr, tpr, _ = roc_curve(label, predict)
|
| 189 |
-
plt.figure(figsize=(8, 8))
|
| 190 |
-
lw = 2
|
| 191 |
-
plt.plot(fpr, tpr, color="darkorange", lw=lw, label="ROC curve (area = %0.4f)" % auc)
|
| 192 |
-
plt.plot([0, 1], [0, 1], color="navy", lw=lw, linestyle="--")
|
| 193 |
-
plt.xlim([0.0, 1.0])
|
| 194 |
-
plt.ylim([0.0, 1.05])
|
| 195 |
-
plt.xlabel("False Positive Rate")
|
| 196 |
-
plt.ylabel("True Positive Rate")
|
| 197 |
-
plt.title("Receiver Operating Characteristic")
|
| 198 |
-
plt.legend(loc="lower right")
|
| 199 |
-
plt.savefig(os.path.join(args.saved_path, "result_auc.png"))
|
| 200 |
-
plt.clf()
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
def plot_result_aupr(args, label, predict, aupr):
|
| 204 |
-
"""
|
| 205 |
-
Plot and save the Precision-Recall (PR) curve.
|
| 206 |
-
|
| 207 |
-
Parameters:
|
| 208 |
-
args: Argument object containing saved_path.
|
| 209 |
-
label (array-like): True labels.
|
| 210 |
-
predict (array-like): Predicted scores.
|
| 211 |
-
aupr (float): Computed AUPR value.
|
| 212 |
-
"""
|
| 213 |
-
# seaborn.set_style()
|
| 214 |
-
precision, recall, _ = precision_recall_curve(label, predict)
|
| 215 |
-
plt.figure(figsize=(8, 8))
|
| 216 |
-
lw = 2
|
| 217 |
-
plt.plot(precision, recall, color="darkorange", lw=lw, label="AUPR (area = %0.4f)" % aupr)
|
| 218 |
-
plt.xlabel("Recall")
|
| 219 |
-
plt.ylabel("Precision")
|
| 220 |
-
plt.title("Precision-Recall Curve")
|
| 221 |
-
plt.legend(loc="lower right")
|
| 222 |
-
plt.savefig(os.path.join(args.saved_path, "result_aupr.png"))
|
| 223 |
-
plt.clf()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|