-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluate.py
More file actions
135 lines (114 loc) · 4.58 KB
/
Copy pathevaluate.py
File metadata and controls
135 lines (114 loc) · 4.58 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
import os
import torch
from torch.utils.data import random_split
import matplotlib.pyplot as plt
import torchvision.transforms as T
from tqdm import tqdm
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, jaccard_score
import numpy as np
import time
from thop import profile
import pandas as pd
import numpy as np
from PIL import Image
import torch
# Evaluation function
def evaluate_model(model, dataloader, results_dir):
model.eval()
all_preds = []
all_labels = []
total_time = 0
total_flops = 0
total_params = 0
results = []
acc_list = []
prec_list = []
rec_list = []
f1_list = []
iou_list = []
with torch.no_grad():
for i, (images, labels, filenames) in enumerate(tqdm(dataloader, desc="Evaluating")):
images = images.to('cuda')
labels = labels.to('cuda')
start_time = time.time()
outputs = model(images)
end_time = time.time()
logits = outputs # Shape: [batch_size, num_classes, height, width]
logits = torch.nn.functional.interpolate(logits, size=labels.shape[-2:], mode="bilinear", align_corners=False)
preds = torch.argmax(logits, dim=1).cpu().numpy() # Shape: [batch_size, height, width]
# Calculate FPS
total_time += end_time - start_time
# Calculate FLOPS and Params once per batch
if i == 0:
flops, params = profile(model, inputs=(images,))
total_flops += flops
total_params += params
# Calculate metrics for each image
for j in range(images.size(0)):
flat_preds = preds[j].flatten()
flat_labels = labels[j].cpu().numpy().flatten()
acc = accuracy_score(flat_labels, flat_preds)
prec = precision_score(flat_labels, flat_preds, average='binary', zero_division=1)
rec = recall_score(flat_labels, flat_preds, average='binary', zero_division=1)
f1 = f1_score(flat_labels, flat_preds, average='binary', zero_division=1)
iou = jaccard_score(flat_labels, flat_preds, average='binary')
acc_list.append(acc)
prec_list.append(prec)
rec_list.append(rec)
f1_list.append(f1)
iou_list.append(iou)
results.append({
"Filename": filenames[j],
"SaveFileName": f'result_{i * dataloader.batch_size + j}.png',
"Accuracy": acc,
"Precision": prec,
"Recall": rec,
"F1 Score": f1,
"IoU": iou
})
# Save results
fig, ax = plt.subplots(1, 3, figsize=(15, 5))
ax[0].imshow(images[j].cpu().permute(1, 2, 0).numpy()) # Convert from CHW to HWC
ax[0].set_title('Image')
ax[0].axis('off')
ax[1].imshow(labels[j].cpu().numpy(), cmap='gray')
ax[1].set_title('Ground Truth')
ax[1].axis('off')
ax[2].imshow(preds[j], cmap='gray')
ax[2].set_title('Prediction')
ax[2].axis('off')
plt.savefig(os.path.join(results_dir, f'result_{i * dataloader.batch_size + j}.png'))
plt.close()
# Calculate average metrics
accuracy = np.mean(acc_list)
precision = np.mean(prec_list)
recall = np.mean(rec_list)
f1 = np.mean(f1_list)
iou = np.mean(iou_list)
fps = len(dataloader.dataset) / total_time
avg_flops = total_flops / len(dataloader.dataset)
avg_params = total_params / len(dataloader.dataset)
# Save evaluation metrics to Excel
evaluation_metrics = {
"Accuracy": [accuracy],
"Precision": [precision],
"Recall": [recall],
"F1 Score": [f1],
"IoU": [iou],
"FPS": [fps],
"Average FLOPS": [avg_flops],
"Average Params": [avg_params]
}
evaluation_df = pd.DataFrame(evaluation_metrics)
evaluation_df.to_excel(os.path.join(results_dir, 'evaluation_metrics.xlsx'), index=False)
# Save per-image metrics to Excel
results_df = pd.DataFrame(results)
results_df.to_excel(os.path.join(results_dir, 'per_image_metrics.xlsx'), index=False)
print(f"Accuracy: {accuracy}")
print(f"Precision: {precision}")
print(f"Recall: {recall}")
print(f"F1 Score: {f1}")
print(f"IoU: {iou}")
print(f"FPS: {fps}")
print(f"Average FLOPS: {avg_flops}")
print(f"Average Params: {avg_params}")