-
Notifications
You must be signed in to change notification settings - Fork 3
/
fid_calculate.py
339 lines (280 loc) · 13.3 KB
/
fid_calculate.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# -*- coding: utf-8 -*-
import torch
from pytorch_fid import fid_score
import pandas as pd
from glob import glob
import os, argparse
import numpy as np
# %%
device = torch.device('cuda' if (torch.cuda.is_available()) else 'cpu')
batch_size = 50
dim = 2048
#path1 = './Datasets/Zurich_patches/fold2/patch_tlevel1/A/test'
#path2 = './Datasets/Zurich_patches_fake/fold2/patch_tlevel1/cyc_A'
# %%
#fid_value = fid_score.calculate_fid_given_paths(
# [path1, path2],
# batch_size, device, dim)
# %%
def calculate_FIDs(dataset, fold=1):
# dataset='Zurich'
# fold=1
assert dataset in ['Balvan', 'Eliceiri', 'Zurich'], "dataset must be in ['Balvan', 'Eliceiri', 'Zurich']"
if dataset == 'Eliceiri':
dataroot_real = f'./Datasets/{dataset}_patches'
dataroot_fake = f'./Datasets/{dataset}_patches_fake'
dataroot_train = f'./Datasets/{dataset}_temp'
else:
dataroot_real = f'./Datasets/{dataset}_patches/fold{fold}'
dataroot_fake = f'./Datasets/{dataset}_patches_fake/fold{fold}'
dataroot_train = f'./Datasets/{dataset}_temp/fold{fold}'
gan_names = ['train2testA', 'train2testB', 'testA', 'testB', 'B2A',
'cyc_A', 'cyc_B', 'drit_A', 'drit_B', 'p2p_A', 'p2p_B', 'star_A', 'star_B', 'comir']
# gan_names = ['cyc_A', 'cyc_B', 'drit_A', 'drit_B', 'p2p_A', 'p2p_B', 'star_A', 'star_B', 'comir', 'B2A']
# csv information
header = [
'Dataset', 'Fold', 'Tlevel', 'GAN_name', 'Path_fake', 'Path_real',
'FID',
]
df = pd.DataFrame(columns=header)
row_dict = {'Dataset': dataset, 'Fold': fold}
for tlevel in [int(tl[-1]) for tl in glob(f'{dataroot_fake}/patch_tlevel*')]:
row_dict['Tlevel'] = tlevel
for gan_name in gan_names:
row_dict['GAN_name'] = gan_name
if gan_name in ['train2testA', 'train2testB']:
row_dict['Path_fake'] = f'{dataroot_train}/{gan_name[-1]}/train/'
row_dict['Path_real'] = f'{dataroot_real}/patch_tlevel{tlevel}/{gan_name[-1]}/test/'
elif gan_name in ['testA', 'testB']:
row_dict['Path_fake'] = f'{dataroot_real}/patch_tlevel{tlevel}/{gan_name[-1]}/test/'
row_dict['Path_real'] = f'{dataroot_real}/patch_tlevel{tlevel}/{gan_name[-1]}/test/'
elif gan_name == 'comir':
row_dict['Path_fake'] = f'{dataroot_fake}/patch_tlevel{tlevel}/{gan_name}_A/'
row_dict['Path_real'] = f'{dataroot_fake}/patch_tlevel{tlevel}/{gan_name}_B/'
elif gan_name == 'B2A':
row_dict['Path_fake'] = f'{dataroot_real}/patch_tlevel{tlevel}/A/test/'
row_dict['Path_real'] = f'{dataroot_real}/patch_tlevel{tlevel}/B/test/'
else:
row_dict['Path_fake'] = f'{dataroot_fake}/patch_tlevel{tlevel}/{gan_name}/'
row_dict['Path_real'] = f'{dataroot_real}/patch_tlevel{tlevel}/{gan_name[-1]}/test/'
row_dict['FID'] = fid_score.calculate_fid_given_paths(
[ row_dict['Path_fake'], row_dict['Path_real'] ],
batch_size, device, dim)
df = df.append(row_dict, ignore_index=True)
result_dir = dataroot_fake
if not os.path.exists(result_dir):
os.makedirs(result_dir)
df.to_csv(f'{result_dir}/FIDs.csv')
return
# %%
def calculate_FIDs_3D(dataset, fold=1):
# dataset='RIRE'
# fold=1
assert dataset in ['RIRE'], "dataset must be in ['RIRE']"
dataroot_real = f'./Datasets/{dataset}_patches_forFID/real/fold{fold}'
dataroot_fake = f'./Datasets/{dataset}_patches_forFID/fake/fold{fold}'
gan_names = ['cyc_A', 'cyc_B', 'drit_A', 'drit_B', 'p2p_A', 'p2p_B', 'star_A', 'star_B', 'comir', 'B2A']
# csv information
header = [
'Dataset', 'Fold', 'Tlevel', 'GAN_name', 'Path_fake', 'Path_real',
'FID',
]
df = pd.DataFrame(columns=header)
row_dict = {'Dataset': dataset, 'Fold': fold}
row_dict['Tlevel'] = 1
for gan_name in gan_names:
row_dict['GAN_name'] = gan_name
if gan_name == 'comir':
row_dict['Path_fake'] = f'{dataroot_fake}/{gan_name}_A/'
row_dict['Path_real'] = f'{dataroot_fake}/{gan_name}_B/'
elif gan_name == 'B2A':
row_dict['Path_fake'] = f'{dataroot_real}/A/test/'
row_dict['Path_real'] = f'{dataroot_real}/B/test/'
else:
row_dict['Path_fake'] = f'{dataroot_fake}/{gan_name}/'
row_dict['Path_real'] = f'{dataroot_real}/{gan_name[-1]}/test/'
row_dict['FID'] = fid_score.calculate_fid_given_paths(
[ row_dict['Path_fake'], row_dict['Path_real'] ],
batch_size, device, dim)
df = df.append(row_dict, ignore_index=True)
result_dir = dataroot_fake
if not os.path.exists(result_dir):
os.makedirs(result_dir)
df.to_csv(f'{result_dir}/FIDs.csv')
return
# %%
def make_FID_success_table(dataset, preprocess='nopre'):
# dataset='Zurich'
# fold=1
assert dataset in ['Balvan', 'Eliceiri', 'Zurich'], "dataset must be in ['Balvan', 'Eliceiri', 'Zurich']"
if dataset == 'Eliceiri':
dataroot_real = f'./Datasets/{dataset}_patches'
path_FIDcsv = f'./Datasets/{dataset}_patches_fake'
w = 834
folds = ['']
else:
dataroot_real = f'./Datasets/{dataset}_patches/fold{{fold}}'
path_FIDcsv = f'./Datasets/{dataset}_patches_fake/fold*'
w = 300
folds = [1, 2, 3]
def success_rate(patches_dir, method, gan_name='', preprocess='nopre', mode='b2a'):
if gan_name in ['A2A', 'B2B', 'B2A']:
gan_name = ''
# read results
dfs = [pd.read_csv(csv_path) for csv_path
in glob(f'{patches_dir}/patch_tlevel*/results/{method+gan_name}_{mode}_{preprocess}.csv')]
whole_df = pd.concat(dfs)
n_success = whole_df['Error'][whole_df['Error'] <= w*0.02].count()
rate_success = n_success / len(whole_df)
# print(f'{method+gan_name}_{preprocess}', rate_success)
return rate_success
# gan_names = ['testA', 'testB', 'B2A',
# 'cyc_A', 'cyc_B', 'drit_A', 'drit_B', 'p2p_A', 'p2p_B', 'star_A', 'star_B', 'comir']
gan_names = ['cyc_A', 'cyc_B', 'drit_A', 'drit_B', 'p2p_A', 'p2p_B', 'star_A', 'star_B', 'comir', 'B2A']
# csv information
header = [
'Method', 'Dataset',
'FID_mean', 'FID_STD',
'Success_aAMD_mean', 'Success_aAMD_STD',
'Success_SIFT_mean', 'Success_SIFT_STD',
]
df = pd.DataFrame(columns=header)
# calculate overall FID
dfs_FID = [pd.read_csv(csv_path) for csv_path
in glob(f'{path_FIDcsv}/FIDs.csv')]
_whole_df_FID = pd.concat(dfs_FID)
_whole_df_FID = _whole_df_FID.drop(columns=[_whole_df_FID.columns[0], 'Tlevel'])
df_FID_grouped = _whole_df_FID.groupby(['GAN_name', 'Fold']).mean().groupby(['GAN_name'])
row_dict = {'Dataset': dataset}
for gan_name in gan_names:
# calculate overall success rate
if gan_name == 'testA':
gan = 'A2A'
direction = 'a2a'
elif gan_name == 'testB':
gan = 'B2B'
direction = 'b2b'
else:
gan = gan_name
direction = 'b2a'
row_dict['Method'] = gan
for reg_method in ['SIFT', 'aAMD']:
l_success = [success_rate(patches_dir=dataroot_real.format(fold=fold),
method=reg_method,
gan_name=gan,
preprocess=preprocess,
mode=direction
) for fold in folds]
row_dict[f'Success_{reg_method}_mean'] = np.mean(l_success)
row_dict[f'Success_{reg_method}_STD'] = np.std(l_success)
row_dict['FID_mean'] = df_FID_grouped.mean().loc[gan_name, 'FID']
row_dict['FID_STD'] = df_FID_grouped.std().loc[gan_name, 'FID']
df = df.append(row_dict, ignore_index=True)
row_dict = {'Dataset': dataset}
for baseline in ['train2testA', 'train2testB']:
row_dict['Method'] = baseline
row_dict['FID_mean'] = df_FID_grouped.mean().loc[baseline, 'FID']
row_dict['FID_STD'] = df_FID_grouped.std().loc[baseline, 'FID']
df = df.append(row_dict, ignore_index=True)
result_dir = f'./Datasets/{dataset}_patches_fake'
if not os.path.exists(result_dir):
os.makedirs(result_dir)
df.to_csv(f'{result_dir}/FID_success_{preprocess}.csv')
return
# %%
def make_FID_success_table_3D(dataset, preprocess='nopre'):
# dataset='RIRE'
# fold=1
assert dataset in ['RIRE'], "dataset must be in ['RIRE']"
dataroot_real = f'./Datasets/{dataset}_patches/fold{{fold}}'
path_FIDcsv = f'./Datasets/{dataset}_slices_fake/fold*'
w = np.asarray((210, 210, 70)).mean()
folds = [1, 2, 3]
def success_rate(patches_dir, method, gan_name='', preprocess='nopre', mode='b2a'):
if gan_name in ['A2A', 'B2B', 'B2A']:
gan_name = ''
# read results
dfs = [pd.read_csv(csv_path) for csv_path
in glob(f'{patches_dir}/patch_tlevel*/results/{method+gan_name}_{mode}_{preprocess}.csv')]
whole_df = pd.concat(dfs)
n_success = whole_df['Error'][whole_df['Error'] <= w*0.02].count()
rate_success = n_success / len(whole_df)
# print(f'{method+gan_name}_{preprocess}', rate_success)
return rate_success
# gan_names = ['testA', 'testB', 'B2A',
# 'cyc_A', 'cyc_B', 'drit_A', 'drit_B', 'p2p_A', 'p2p_B', 'star_A', 'star_B', 'comir']
gan_names = ['cyc_A', 'cyc_B', 'drit_A', 'drit_B', 'p2p_A', 'p2p_B', 'star_A', 'star_B', 'comir', 'B2A']
# csv information
header = [
'Method', 'Dataset',
'FID_mean', 'FID_STD',
'Success_aAMD_mean', 'Success_aAMD_STD',
# 'Success_SIFT_mean', 'Success_SIFT_STD',
]
df = pd.DataFrame(columns=header)
# calculate overall FID
dfs_FID = [pd.read_csv(csv_path) for csv_path
in glob(f'{path_FIDcsv}/FIDs.csv')]
_whole_df_FID = pd.concat(dfs_FID)
_whole_df_FID = _whole_df_FID.drop(columns=[_whole_df_FID.columns[0], 'Tlevel'])
df_FID_grouped = _whole_df_FID.groupby(['GAN_name', 'Fold']).mean().groupby(['GAN_name'])
row_dict = {'Dataset': dataset}
for gan_name in gan_names:
# calculate overall success rate
if gan_name == 'testA':
gan = 'A2A'
direction = 'a2a'
elif gan_name == 'testB':
gan = 'B2B'
direction = 'b2b'
else:
gan = gan_name
direction = 'b2a'
row_dict['Method'] = gan
for reg_method in ['aAMD']:
l_success = [success_rate(patches_dir=dataroot_real.format(fold=fold),
method=reg_method,
gan_name=gan,
preprocess=preprocess,
mode=direction
) for fold in folds]
row_dict[f'Success_{reg_method}_mean'] = np.mean(l_success)
row_dict[f'Success_{reg_method}_STD'] = np.std(l_success)
row_dict['FID_mean'] = df_FID_grouped.mean().loc[gan_name, 'FID']
row_dict['FID_STD'] = df_FID_grouped.std().loc[gan_name, 'FID']
df = df.append(row_dict, ignore_index=True)
# row_dict = {'Dataset': dataset}
# for baseline in ['train2testA', 'train2testB']:
# row_dict['Method'] = baseline
# row_dict['FID_mean'] = df_FID_grouped.mean().loc[baseline, 'FID']
# row_dict['FID_STD'] = df_FID_grouped.std().loc[baseline, 'FID']
# df = df.append(row_dict, ignore_index=True)
result_dir = f'./Datasets/{dataset}_slices_fake'
if not os.path.exists(result_dir):
os.makedirs(result_dir)
df.to_csv(f'{result_dir}/FID_success_{preprocess}.csv')
return
# %%
if __name__ == '__main__':
# for running from terminal
parser = argparse.ArgumentParser(description='Calculate FIDs for generated patches.')
parser.add_argument(
'--dataset', '-d',
help="dataset",
choices=['Balvan', 'Eliceiri', 'Zurich', 'RIRE'],
default='Zurich')
parser.add_argument(
'--fold', '-f',
help="fold",
type=int,
choices=[1, 2, 3],
default=1)
args = parser.parse_args()
if args.dataset == 'RIRE':
calculate_FIDs_3D(dataset=args.dataset, fold=args.fold)
else:
calculate_FIDs(dataset=args.dataset, fold=args.fold)
# for pre in ['nopre']:
# for dataset in ['Balvan', 'Eliceiri', 'Zurich']:
# make_FID_success_table(dataset=dataset, preprocess=pre)
make_FID_success_table_3D(dataset='RIRE')