-
Notifications
You must be signed in to change notification settings - Fork 26
/
eval.py
307 lines (241 loc) · 10.7 KB
/
eval.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 sys
import argparse
import numpy as np
import pandas as pd
import cv2
import matplotlib.pyplot as plt
from tqdm import tqdm
import torch
import torch.nn.functional as TF
import torch.backends.cudnn as cudnn
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from pytvision.transforms.aumentation import ObjectImageMetadataTransform
from pytvision.transforms import transforms as mtrans
#sys.path.append('../')
from torchlib.transforms import functional as F
from torchlib.datasets.fersynthetic import SyntheticFaceDataset
from torchlib.datasets.factory import FactoryDataset
from torchlib.datasets.datasets import Dataset
from torchlib.datasets.fersynthetic import SyntheticFaceDataset
from torchlib.attentionnet import AttentionNeuralNet
from aug import get_transforms_aug, get_transforms_det
# METRICS
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
from sklearn.naive_bayes import GaussianNB
import sklearn.metrics as metrics
from argparse import ArgumentParser
def arg_parser():
"""Arg parser"""
parser = ArgumentParser()
parser.add_argument('--project', metavar='DIR', help='path to projects')
parser.add_argument('--projectname', metavar='DIR', help='name projects')
parser.add_argument('--pathdataset', metavar='DIR', help='path to dataset')
parser.add_argument('--namedataset', metavar='S', help='name to dataset')
parser.add_argument('--pathnameout', metavar='DIR', help='path to out dataset')
parser.add_argument('--filename', metavar='S', help='name of the file output')
parser.add_argument('--model', metavar='S', help='filename model')
return parser
def main():
parser = arg_parser();
args = parser.parse_args();
# Configuration
project = args.project
projectname = args.projectname
pathnamedataset = args.pathdataset
pathnamemodel = args.model
pathproject = os.path.join( project, projectname )
pathnameout = args.pathnameout
filename = args.filename
namedataset = args.namedataset
no_cuda=False
parallel=False
gpu=0
seed=1
brepresentation=True
bclassification_test=True
brecover_test=True
imagesize=64
idenselect=np.arange(10)
# experiments
experiments = [
{ 'name': namedataset, 'subset': FactoryDataset.training, 'real': True },
{ 'name': namedataset, 'subset': FactoryDataset.validation, 'real': True },
{ 'name': namedataset+'dark', 'subset': FactoryDataset.training, 'real': False },
{ 'name': namedataset+'dark', 'subset': FactoryDataset.validation, 'real': False },
]
# representation datasets
if brepresentation:
# Load models
print('>> Load model ...')
network = AttentionNeuralNet(
patchproject=project,
nameproject=projectname,
no_cuda=no_cuda,
parallel=parallel,
seed=seed,
gpu=gpu,
)
cudnn.benchmark = True
# load model
if network.load( pathnamemodel ) is not True:
print('>>Error!!! load model')
assert(False)
size_input = network.size_input
for i, experiment in enumerate(experiments):
name_dataset = experiment['name']
subset = experiment['subset']
breal = experiment['real']
dataset = []
# load dataset
if breal:
# real dataset
dataset = Dataset(
data=FactoryDataset.factory(
pathname=pathnamedataset,
name=namedataset,
subset=subset,
idenselect=idenselect,
download=True
),
num_channels=3,
transform=get_transforms_det( imagesize ),
)
else:
# synthetic dataset
dataset = SyntheticFaceDataset(
data=FactoryDataset.factory(
pathname=pathnamedataset,
name=namedataset,
subset=subset,
idenselect=idenselect,
download=True
),
pathnameback='~/.datasets/coco',
ext='jpg',
count=2000,
num_channels=3,
iluminate=True, angle=45, translation=0.3, warp=0.2, factor=0.2,
transform_data=get_transforms_aug( imagesize ),
transform_image=get_transforms_det( imagesize ),
)
dataloader = DataLoader(dataset, batch_size=100, shuffle=False, num_workers=10 )
print(breal)
print(subset)
print(dataloader.dataset.data.classes)
print(len(dataset))
print(len(dataloader))
# representation
Y_labs, Y_lab_hats, Zs = network.representation( dataloader, breal )
print(Y_lab_hats.shape, Zs.shape, Y_labs.shape)
reppathname = os.path.join( pathproject, 'rep_{}_{}_{}_{}.pth'.format(projectname, namedataset, subset, 'real' if breal else 'no_real' ) )
torch.save( { 'Yh':Y_lab_hats, 'Z':Zs, 'Y':Y_labs }, reppathname )
print( 'save representation ...' )
if bclassification_test:
tuplas=[]
print('|Num\t|Acc\t|Prec\t|Rec\t|F1\t|Set\t|Type\t')
for i, experiment in enumerate(experiments):
name_dataset = experiment['name']
subset = experiment['subset']
breal = experiment['real']
real = 'real' if breal else 'no_real'
rep_pathname = os.path.join( pathproject, 'rep_{}_{}_{}_{}.pth'.format(
projectname, namedataset, subset, real) )
data_emb = torch.load(rep_pathname)
Xto = data_emb['Z']
Yto = data_emb['Y']
Yho = data_emb['Yh']
yhat = np.argmax( Yho, axis=1 )
y = Yto
acc = metrics.accuracy_score(y, yhat)
precision = metrics.precision_score(y, yhat, average='macro')
recall = metrics.recall_score(y, yhat, average='macro')
f1_score = 2*precision*recall/(precision+recall)
print( '|{}\t|{:0.3f}\t|{:0.3f}\t|{:0.3f}\t|{:0.3f}\t|{}\t|{}\t'.format(
i,
acc, precision, recall, f1_score,
subset, real,
).replace('.',',') )
#|Name|Dataset|Cls|Acc| ...
tupla = {
'Name':projectname,
'Dataset': '{}({})_{}'.format( name_dataset, subset, real ),
'Accuracy': acc,
'Precision': precision,
'Recall': recall,
'F1 score': f1_score,
}
tuplas.append(tupla)
# save
df = pd.DataFrame(tuplas)
df.to_csv( os.path.join( pathnameout, 'experiments_cls.csv' ) , index=False, encoding='utf-8')
print('save experiments class ...')
print()
if brecover_test:
experiments = [
{ 'name': namedataset, 'train': True, 'val': True },
{ 'name': namedataset, 'train': False, 'val': False },
{ 'name': namedataset, 'train': False, 'val': True },
{ 'name': namedataset, 'train': True, 'val': False },
]
tuplas=[]
print('|Num\t|Acc\t|Prec\t|Rec\t|F1\t|Type\t')
for i, experiment in enumerate(experiments):
name_dataset = experiment['name']
real_train = 'real' if experiment['train'] else 'no_real'
real_val = 'real' if experiment['val'] else 'no_real'
rep_trn_pathname = os.path.join( pathproject, 'rep_{}_{}_{}_{}.pth'.format(projectname, name_dataset, 'train', real_train) )
rep_val_pathname = os.path.join( pathproject, 'rep_{}_{}_{}_{}.pth'.format(projectname, name_dataset, 'val', real_val) )
data_emb_train = torch.load(rep_trn_pathname)
data_emb_val = torch.load(rep_val_pathname)
Xo = data_emb_train['Z']
Yo = data_emb_train['Y']
Xto = data_emb_val['Z']
Yto = data_emb_val['Y']
clf = KNeighborsClassifier(n_neighbors=11)
#clf = GaussianNB()
#clf = RandomForestClassifier(n_estimators=150, oob_score=True, random_state=123456)
#clf = MLPClassifier(hidden_layer_sizes=(100,100), max_iter=100, alpha=1e-4,
# solver='sgd', verbose=10, tol=1e-4, random_state=1,
# learning_rate_init=.01)
clf.fit(Xo,Yo)
y = Yto
yhat = clf.predict(Xto)
acc = metrics.accuracy_score(y, yhat)
nmi_s = metrics.cluster.normalized_mutual_info_score(y, yhat)
mi = metrics.cluster.mutual_info_score(y, yhat)
h1 = metrics.cluster.entropy(y)
h2 = metrics.cluster.entropy(yhat)
nmi = 2*mi/(h1+h2)
precision = metrics.precision_score(y, yhat, average='macro')
recall = metrics.recall_score(y, yhat, average='macro')
f1_score = 2*precision*recall/(precision+recall)
#|Name|Dataset|Cls|Acc| ...
tupla = {
'Name':projectname,
'Dataset': '{}({}_{})'.format( name_dataset, real_train, real_val ),
'Accuracy': acc,
'NMI': nmi_s,
'Precision': precision,
'Recall': recall,
'F1 score': f1_score,
}
tuplas.append(tupla)
print( '|{}\t|{:0.3f}\t|{:0.3f}\t|{:0.3f}\t|{:0.3f}\t|{}/{}\t'.format(
i,
acc, precision, recall, f1_score,
real_train, real_val,
).replace('.',',')
)
# save
df = pd.DataFrame(tuplas)
df.to_csv( os.path.join( pathnameout, 'experiments_recovery.csv' ) , index=False, encoding='utf-8')
print('save experiments recovery ...')
print()
print('DONE!!!')
if __name__ == '__main__':
main()