-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtesting.py
136 lines (105 loc) · 3.68 KB
/
testing.py
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
# Import libraries
import math
import torch
import numpy as np
from torch.utils.data import DataLoader
from sklearn.metrics import confusion_matrix, roc_curve, roc_auc_score
# Import local modules
from helper_functions import plot_roc_curve
# Define a function to evaluate a PyTorch model
def evaluate_model(model, dataset, verbose=True, plot=False):
"""Evaluate a PyTorch model on a dataset."""
### EVALUATE THE MODEL ###
if verbose:
status = f'Evaluating model with {sum(p.numel() for p in model.parameters())} parameters.'
print(status)
# Set up model and device
model.eval()
device = next(model.parameters()).device
# Set up the dataloader
dataloader = DataLoader(dataset, batch_size=1, shuffle=False)
# Determine downsample factor
n_images = len(dataloader)
n_pixels = math.prod(next(iter(dataloader))[0].shape)
n_samples = n_images * n_pixels
if n_samples > 100000:
n_samples_per_img = 100000 // n_images
else:
n_samples_per_img = n_pixels
# Create lists
true_labels = []
predicted_probs = []
predicted_labels = []
# Iterate over the dataloader
for i, (x, y) in enumerate(dataloader):
if verbose and (((i+1)%100==0) or (i==len(dataloader)-1) or (len(dataloader)<20)):
print(f'--Image {i + 1}/{len(dataloader)}')
# Move the data to the device
x = x.to(device)
y = y.to(device)
# Forward pass through the model
z = model(x)
# Get the predicted probabilities and labels
probs = torch.softmax(z, dim=1)
labels = torch.argmax(probs, dim=1)
# Flatten the data
trues = y.cpu().numpy().reshape(-1)
probs = probs[:, 1].cpu().detach().numpy().reshape(-1)
labels = labels.cpu().numpy().reshape(-1)
# Randomly sample the indices
indices = np.random.choice(len(trues), min(n_samples_per_img, len(trues)), replace=False)
trues = trues[indices]
probs = probs[indices]
labels = labels[indices]
# Append results to lists
true_labels.extend(trues)
predicted_probs.extend(probs)
predicted_labels.extend(labels)
# Convert the lists to numpy arrays
true_labels = np.array(true_labels)
predicted_probs = np.array(predicted_probs)
predicted_labels = np.array(predicted_labels)
### CALCULATE EVALUATION METRICS ###
if verbose:
print('Calculating evaluation metrics.')
# Calculate the confusion matrix
tn, fp, fn, tp = confusion_matrix(
true_labels,
predicted_labels,
).ravel()
# Calculate sensitivity, specificity, and accuracy
sensitivity = tp / (tp + fn)
specificity = tn / (tn + fp)
accuracy = (tp + tn) / (tp + tn + fp + fn)
f1score = 2 * tp / (2 * tp + fp + fn)
### CALCULATE ROC CURVE AND AUC SCORE ###
if verbose:
print('Calculating ROC curve and AUC score.')
# Calculate the ROC curve and AUC score
roc_fpr, roc_tpr, roc_thresholds = roc_curve(
true_labels,
predicted_probs,
)
auc_score = roc_auc_score(
true_labels,
predicted_probs,
)
# Plot the ROC curve
if plot:
plot_roc_curve(roc_fpr, roc_tpr, auc_score)
### PACKAGE THE METRICS ###
if verbose:
print('Packaging the metrics.')
# Package the metrics in a dictionary
metrics = {
'accuracy': accuracy,
'sensitivity': sensitivity,
'specificity': specificity,
'f1score': f1score,
'auc_score': auc_score,
'roc_fpr': roc_fpr,
'roc_tpr': roc_tpr,
'roc_thresholds': roc_thresholds,
}
# Return the evaluation metrics
return metrics