-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinference.py
141 lines (113 loc) · 4.97 KB
/
inference.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
135
136
137
138
139
140
141
import sys
import os
import argparse
import numpy as np
import torch
import torch.nn as nn
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score, confusion_matrix
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from tqdm import tqdm
from PIL import Image
import time
from data.transforms import test_transforms
from models.EfficientNet import EfficientNetBinaryClassifier
class InferenceDataset(datasets.VisionDataset):
def __init__(self, root_dir, transform=None):
super().__init__(root_dir, transform=transform)
self.root_dir = root_dir
self.transform = transform
self.image_paths = []
for label in ['aligned', 'not_aligned']:
folder_path = os.path.join(root_dir, label)
self.image_paths.extend([(os.path.join(folder_path, img), label)
for img in os.listdir(folder_path) if img.endswith(('png', 'jpg', 'jpeg'))])
def __len__(self):
return len(self.image_paths)
def __getitem__(self, idx):
img_path, label = self.image_paths[idx]
image = Image.open(img_path).convert("RGB")
label = 1 if label == "aligned" else 0
if self.transform:
image = self.transform(image)
return image, label
def evaluate_model(model, test_loader, device, beta=0.5):
model.eval()
all_labels = []
all_predictions = []
inference_times = [] # List to store inference times
with torch.no_grad():
for images, labels in tqdm(test_loader):
images, labels = images.to(device), labels.to(device)
labels = labels.unsqueeze(1).to(torch.float32)
# Start time for inference
start_time = time.time()
outputs = model(images)
predicted = (outputs > 0.5).float()
# End time and calculate duration
end_time = time.time()
inference_time = end_time - start_time
inference_times.append(inference_time) # Store the duration
all_labels.extend(labels.cpu().detach().numpy().astype(int))
all_predictions.extend(predicted.cpu().detach().numpy().astype(int))
# Convert lists to numpy arrays for metric calculations
all_labels = np.array(all_labels).flatten()
all_predictions = np.array(all_predictions).flatten()
# Calculate evaluation metrics
accuracy = accuracy_score(all_labels, all_predictions)
precision = precision_score(all_labels, all_predictions)
recall = recall_score(all_labels, all_predictions)
f1 = f1_score(all_labels, all_predictions)
fbeta = fbeta_score(all_labels, all_predictions, beta=beta)
confusion = confusion_matrix(all_labels, all_predictions)
print(f"Accuracy: {accuracy:.4f}")
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1 Score: {f1:.4f}")
print(f"F-beta Score (beta={beta}): {fbeta:.4f}")
print(f"Confusion Matrix:\n{confusion}")
# Calculate statistics on inference times
inference_times = np.array(inference_times)
mean_time = np.mean(inference_times)
quantiles = np.quantile(inference_times, [0.25, 0.5, 0.75])
print(f"\nInference Time Statistics:")
print(f"Mean Time: {mean_time:.4f} seconds")
print(f"25th Percentile: {quantiles[0]:.4f} seconds")
print(f"Median (50th Percentile): {quantiles[1]:.4f} seconds")
print(f"75th Percentile: {quantiles[2]:.4f} seconds")
def main(args):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Evaluating on: {device}")
# Load test data
test_dataset = InferenceDataset(root_dir=args.s,
transform=test_transforms)
test_loader = DataLoader(test_dataset,
batch_size=args.batch_size,
shuffle=False)
# Load model
model = EfficientNetBinaryClassifier()
model = nn.DataParallel(model)
model.load_state_dict(torch.load(args.model_path)["model_state_dict"])
model = model.to(device)
# Evaluate model
evaluate_model(model, test_loader, device, beta=0.5)
def argument_parser():
parser = argparse.ArgumentParser(description="Evaluate EfficientNet on Duferco test dataset")
parser.add_argument('--s',
type=str,
required=True,
help='Path to dataset')
parser.add_argument('--batch_size',
type=int,
default=16,
help='Batch size')
parser.add_argument('--model_path',
type=str,
default='checkpoints/efficient_net/20241027_083453/model_epoch_5.pt',
help='Path to the trained model checkpoint')
args = parser.parse_args()
return args
if __name__ == '__main__':
args = argument_parser()
main(args)