-
Notifications
You must be signed in to change notification settings - Fork 0
/
P3_inference.py
156 lines (134 loc) · 4.26 KB
/
P3_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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import argparse
import csv
import pathlib
import numpy as np
import torch
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from P3_SVHN_model import FeatureExtractor as SF
from P3_SVHN_model import LabelPredictor as SL
from P3_USPS_model import FeatureExtractor as UF
from P3_USPS_model import LabelPredictor as UL
class ImageFolderTestPNGDataset(Dataset):
def __init__(self, path, transform):
path = pathlib.Path(path)
self.data = []
for img in path.glob("*"):
if img.is_file():
self.data.append(img)
self.transform = transform
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
img_path = self.data[idx]
img = Image.open(img_path).convert('RGB')
return self.transform(img), img_path.name
def main(args):
USPS = 'usps' in str(args.input_dir)
if USPS:
mean, std = [0.2573, 0.2573, 0.2573], [0.3373, 0.3373, 0.3373]
else:
mean, std = [0.4413, 0.4458, 0.4715], [0.1169, 0.1206, 0.1042]
print(f'mean, std = {mean}, {std}')
dataset = ImageFolderTestPNGDataset(
args.input_dir,
transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean, std)
]),
)
test_loader = DataLoader(dataset, batch_size=64,
shuffle=False, num_workers=6)
if USPS:
print('loading usps model')
F = UF().to(args.device)
L = UL().to(args.device)
F.load_state_dict(torch.load(
args.usps_ckpt / "best_F.pth", map_location=args.device))
L.load_state_dict(torch.load(
args.usps_ckpt / "best_L.pth", map_location=args.device))
else:
print('loading svhn model')
F = SF().to(args.device)
L = SL().to(args.device)
F.load_state_dict(torch.load(
args.svhn_ckpt / "best_F.pth", map_location=args.device))
L.load_state_dict(torch.load(
args.svhn_ckpt / "best_L.pth", map_location=args.device))
F.eval()
L.eval()
all_preds = []
all_names = []
for tgt_x, names in test_loader:
tgt_x = tgt_x.to(args.device)
with torch.no_grad():
logits = L(F(tgt_x))
pred = logits.argmax(-1).cpu().tolist()
all_preds.extend(pred)
all_names.extend(names)
with open(args.out_csv, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(('image_name', 'label'))
for data in zip(all_names, all_preds):
writer.writerow(data)
# validation result
try:
if args.do_eval:
cor = 0
total = 0
with open(f'hw2_data/digits/{"usps" if USPS else "svhn"}/val.csv', 'r') as file:
reader = csv.reader(file)
next(iter(reader)) # ignore first line
for row in reader:
name, gt = row[0], int(row[1])
if gt == all_preds[all_names.index(name)]:
cor += 1
total += 1
print(cor / total)
except Exception as e:
print(e)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-uw", "--usps_ckpt",
help="directory of usps weight",
type=pathlib.Path,
default='./P3_USPS_ckpt/'
)
parser.add_argument(
"-sw", "--svhn_ckpt",
help="directory of svhn weight",
type=pathlib.Path,
default='./P3_SVHN_ckpt/'
)
parser.add_argument(
"-i", "--input_dir",
help="directory of input images",
type=pathlib.Path,
required=True,
)
parser.add_argument(
"-o", "--out_csv",
help="path to output csv",
type=pathlib.Path,
required=True,
)
parser.add_argument(
"-d", "--device",
help="device",
type=torch.device,
default='cuda' if torch.cuda.is_available() else 'cpu',
)
parser.add_argument(
"-v", "--do_eval",
action='store_true',
)
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
try:
args.out_csv.parents[0].mkdir(exist_ok=True, parents=True)
except:
pass
main(args)