This repository has been archived by the owner on Jan 5, 2024. It is now read-only.
forked from KonradHabel/clip_reid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpredict.py
307 lines (246 loc) · 12.4 KB
/
predict.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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import os
import torch
import pandas as pd
import numpy as np
from dataclasses import dataclass
from torch.utils.data import DataLoader
from clipreid.model import TimmModel, OpenClipModel
from clipreid.transforms import get_transforms
from clipreid.dataset import TestDataset, ChallengeDataset
from clipreid.evaluator import predict, compute_dist_matrix, compute_scores, write_mat_csv
from clipreid.utils import print_line
@dataclass
class Configuration:
'''
--------------------------------------------------------------------------
Open Clip Models:
--------------------------------------------------------------------------
- ('RN50', 'openai')
- ('RN50', 'yfcc15m')
- ('RN50', 'cc12m')
- ('RN50-quickgelu', 'openai')
- ('RN50-quickgelu', 'yfcc15m')
- ('RN50-quickgelu', 'cc12m')
- ('RN101', 'openai')
- ('RN101', 'yfcc15m')
- ('RN101-quickgelu', 'openai')
- ('RN101-quickgelu', 'yfcc15m')
- ('RN50x4', 'openai')
- ('RN50x16', 'openai')
- ('RN50x64', 'openai')
- ('ViT-B-32', 'openai')
- ('ViT-B-32', 'laion2b_e16')
- ('ViT-B-32', 'laion400m_e31')
- ('ViT-B-32', 'laion400m_e32')
- ('ViT-B-32-quickgelu', 'openai')
- ('ViT-B-32-quickgelu', 'laion400m_e31')
- ('ViT-B-32-quickgelu', 'laion400m_e32')
- ('ViT-B-16', 'openai')
- ('ViT-B-16', 'laion400m_e31')
- ('ViT-B-16', 'laion400m_e32')
- ('ViT-B-16-plus-240', 'laion400m_e31')
- ('ViT-B-16-plus-240', 'laion400m_e32')
- ('ViT-L-14', 'openai')
- ('ViT-L-14', 'laion400m_e31')
- ('ViT-L-14', 'laion400m_e32')
- ('ViT-L-14-336', 'openai')
- ('ViT-H-14', 'laion2b_s32b_b79k')
- ('ViT-g-14', 'laion2b_s12b_b42k')
--------------------------------------------------------------------------
Timm Models:
--------------------------------------------------------------------------
- 'convnext_base_in22ft1k'
- 'convnext_large_in22ft1k'
- 'vit_base_patch16_224'
- 'vit_large_patch16_224'
- ...
- https://github.com/rwightman/pytorch-image-models/blob/master/results/results-imagenet.csv
--------------------------------------------------------------------------
'''
# Model
model: str = ('ViT-L-14', 'openai') # ('name of Clip model', 'name of dataset') | 'name of Timm model'
remove_proj = True # remove projection for Clip ViT models
# Settings only for Timm models
img_size: int = (224, 224) # follow above Link for image size of Timm models
mean: float = (0.485, 0.456, 0.406) # mean of ImageNet
std: float = (0.229, 0.224, 0.225) # std of ImageNet
# Eval
batch_size: int = 64 # batch size for evaluation
normalize_features: int = True # L2 normalize of features during eval
# Split for Eval
fold: int = -1 # -1 for given test split | int >=0 for custom folds
# Checkpoints: str or tuple of str for ensemble (checkpoint1, checkpoint2, ...)
checkpoints: str = ("./model/ViT-L-14_openai/fold-1_seed_1/weights_e4.pth",
"./model/ViT-L-14_openai/all_data_seed_1/weights_e4.pth")
#checkpoints: str = "./model/ViT-L-14_openai/Paper/weights_e4.pth"
# Dataset
data_dir: str = "./data/data_reid"
# show progress bar
verbose: bool = True
# set num_workers to 0 if OS is Windows
num_workers: int = 0 if os.name == 'nt' else 8
# use GPU if available
device: str = 'cuda:0' if torch.cuda.is_available() else 'cpu'
#----------------------------------------------------------------------------------------------------------------------#
# Config #
#----------------------------------------------------------------------------------------------------------------------#
config = Configuration()
#----------------------------------------------------------------------------------------------------------------------#
# Model #
#----------------------------------------------------------------------------------------------------------------------#
print("\nModel: {}".format(config.model))
if isinstance(config.model, tuple):
model = OpenClipModel(config.model[0],
config.model[1],
remove_proj=config.remove_proj
)
img_size = model.get_image_size()
mean=(0.48145466, 0.4578275, 0.40821073)
std=(0.26862954, 0.26130258, 0.27577711)
else:
model = TimmModel(config.model,
pretrained=True)
img_size = config.img_size
mean = config.mean
std = config.std
dist_matrix_list = []
dist_matrix_rerank_list = []
if not isinstance(config.checkpoints, list) and not isinstance(config.checkpoints, tuple):
checkpoints = [config.checkpoints]
else:
checkpoints = config.checkpoints
for checkpoint in checkpoints:
print_line(name=checkpoint, length=80)
# load pretrained Checkpoint
model_state_dict = torch.load(checkpoint)
model.load_state_dict(model_state_dict, strict=True)
# Model to device
model = model.to(config.device)
print("\nImage Size:", img_size)
print("Mean: {}".format(mean))
print("Std: {}".format(std))
#------------------------------------------------------------------------------------------------------------------#
# DataLoader #
#------------------------------------------------------------------------------------------------------------------#
# Transforms
val_transforms, train_transforms = get_transforms(img_size, mean, std)
# Dataframes
df = pd.read_csv("./data/data_reid/train_df.csv")
df_challenge = pd.read_csv("./data/data_reid/challenge_df.csv")
if config.fold == -1:
# Use given test split
df_train = df[df["split"] == "train"]
df_test = df[df["split"] == "test"]
else:
# Use custom folds
df_train = df[df["fold"] != config.fold]
df_test = df[df["fold"] == config.fold]
# Validation
test_dataset = TestDataset(img_path="./data/data_reid",
df=df_test,
image_transforms=val_transforms)
test_loader = DataLoader(test_dataset,
batch_size=config.batch_size,
num_workers=config.num_workers,
shuffle=False,
pin_memory=True)
# Challenge
challenge_dataset = ChallengeDataset(df=df_challenge,
image_transforms=val_transforms)
challenge_loader = DataLoader(challenge_dataset,
batch_size=config.batch_size,
num_workers=config.num_workers,
shuffle=False,
pin_memory=True)
#------------------------------------------------------------------------------------------------------------------#
# Test #
#------------------------------------------------------------------------------------------------------------------#
print_line(name="Eval Fold: {}".format(config.fold), length=80)
# extract features
features_dict = predict(model,
dataloader=test_loader,
device=config.device,
normalize_features=config.normalize_features,
verbose=config.verbose)
# compute distance matrix
dist_matrix_test, dist_matrix_test_rerank = compute_dist_matrix(features_dict,
test_dataset.query,
test_dataset.gallery,
rerank=True)
# without re-ranking
print("\nwithout re-ranking:")
mAP = compute_scores(dist_matrix_test,
test_dataset.query,
test_dataset.gallery,
cmc_scores=True)
save_path = '{}/test_dmat.csv'.format("/".join(checkpoint.split("/")[:-1]))
print("write distance matrix:", save_path)
write_mat_csv(save_path,
dist_matrix_test,
test_dataset.query,
test_dataset.gallery)
# save with re-ranking
print("\nwith re-ranking:")
mAP = compute_scores(dist_matrix_test_rerank,
test_dataset.query,
test_dataset.gallery,
cmc_scores=True)
save_path = '{}/test_dmat_rerank.csv'.format("/".join(checkpoint.split("/")[:-1]))
print("write distance matrix:", save_path)
write_mat_csv(save_path,
dist_matrix_test_rerank,
test_dataset.query,
test_dataset.gallery)
#------------------------------------------------------------------------------------------------------------------#
# Challenge #
#------------------------------------------------------------------------------------------------------------------#
print_line(name="Challenge", length=80)
# extract features
features_dict = predict(model,
dataloader=challenge_loader,
device=config.device,
normalize_features=config.normalize_features,
verbose=config.verbose)
# compute distance matrix
dist_matrix, dist_matrix_rerank = compute_dist_matrix(features_dict,
challenge_dataset.query,
challenge_dataset.gallery,
rerank=True)
# collect for ensemble
dist_matrix_list.append(dist_matrix)
dist_matrix_rerank_list.append(dist_matrix_rerank)
# save without re-ranking
save_path = '{}/challenge_dmat.csv'.format("/".join(checkpoint.split("/")[:-1]))
print("write distance matrix:", save_path)
write_mat_csv(save_path,
dist_matrix,
challenge_dataset.query,
challenge_dataset.gallery)
# save with re-ranking
save_path = '{}/challenge_dmat_rerank.csv'.format("/".join(checkpoint.split("/")[:-1]))
print("write distance matrix:", save_path)
write_mat_csv(save_path,
dist_matrix_rerank,
challenge_dataset.query,
challenge_dataset.gallery)
#----------------------------------------------------------------------------------------------------------------------#
# Ensemble #
#----------------------------------------------------------------------------------------------------------------------#
if len(dist_matrix_list) > 1:
print_line(name="Ensemble", length=80)
# without re-ranking
dist_matrix_ensemble = np.stack(dist_matrix_list, axis=0).mean(0)
save_path = '{}/challenge_dmat_ensemble.csv'.format("/".join(checkpoint.split("/")[:-2]))
print("write distance matrix:", save_path)
write_mat_csv(save_path,
dist_matrix_ensemble,
challenge_dataset.query,
challenge_dataset.gallery)
# with re-ranking
dist_matrix_rerank_ensemble = np.stack(dist_matrix_rerank_list, axis=0).mean(0)
save_path = '{}/challenge_dmat_rerank_ensemble.csv'.format("/".join(checkpoint.split("/")[:-2]))
print("write distance matrix:", save_path)
write_mat_csv(save_path,
dist_matrix_rerank_ensemble,
challenge_dataset.query,
challenge_dataset.gallery)