-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_lstm_emb.py
219 lines (197 loc) · 5.94 KB
/
get_lstm_emb.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
import tensorflow as tf
import keras
from keras import Sequential, regularizers
from keras.backend import categorical_crossentropy
from keras.layers import ConvLSTM2D, Flatten, Dense, BatchNormalization, MaxPool2D, MaxPool3D
from keras.constraints import Constraint
from keras.constraints import max_norm
from keras.callbacks import ModelCheckpoint
from keras.layers import LeakyReLU, Dropout
from keras.models import load_model
from keras.models import Model
from keras.optimizers import Adadelta
import cv2
import pdb
import numpy as np
import os
import random
from sklearn import metrics
import createmodel
import sys
from utils import switch
kernel = [[-1, 2, -2, 2, -1],
[2, -6, 8, -6, 2],
[-2, 8, -12, 8, -2],
[2, -6, 8, -6, 2],
[-1, 2, -2, 2, -1]]
kernel = np.array((kernel), dtype="float32")
rrate = int(sys.argv[1])
#rrate = 3
data = []
y = []
trainx = []
trainy = []
testx = []
testy = []
real_path = '/mnt/celeb-real-lstm/'
#fake_path = '/mnt/celeb-synthesis-lstm/'
#real_path = '/mnt/celeb-real-eye/'
fake_path = '/mnt/celeb-synthesis-eye/'
#pdb.set_trace()
lstmnum = 4
capnum = 7
alltotal = int(sys.argv[2])
#alltotal = 800
total = alltotal
ttname = ''
vdname = ''
fflag = 1
for name in os.listdir(real_path):
dd = []
if total <= 0:
break
#print(name)
vdname = '_'.join(name.split('_')[:2])
num = int(name.split('.')[0].split('_')[2])
nn = '_'.join(name.split('.')[0].split('_')[:2])
if num < capnum-lstmnum:
try:
for i in range(lstmnum):
imgname = nn+'_'+str(num+i)+'.jpg'
img = cv2.imread(real_path+imgname)
img = cv2.resize(img, (128, 100))
img = cv2.filter2D(img, -1, kernel)
dd.append(img)
dd = np.array(dd)
except:
print(name)
continue
if total > alltotal * 0.2:
trainx.append(dd)
trainy.append([1, 0])
else:
if vdname == 'ttname' and fflag:
continue
fflag = 0
testx.append(dd)
testy.append([1, 0])
total -= 1
ttname = vdname
#pdb.set_trace()
print(len(trainx), len(testx))
podata = len(testy)
total = alltotal*rrate
ftotal = alltotal*rrate
fflag = 1
for name in os.listdir(fake_path):
#if np.random.randint(2) == 1:
# continue
dd = []
if ftotal <= 0:
break
vdname = '_'.join(name.split('_')[:3])
num = int(name.split('.')[0].split('_')[3])
nn = '_'.join(name.split('.')[0].split('_')[:3])
if num < capnum-lstmnum:
try:
for i in range(lstmnum):
imgname = nn + '_' + str(num + i) + '.jpg'
img = cv2.imread(fake_path + imgname)
img = cv2.resize(img, (128, 100))
img = cv2.filter2D(img, -1, kernel)
dd.append(img)
dd = np.array(dd)
except:
print(name)
continue
if ftotal > total * 0.2:
trainx.append(dd)
trainy.append([0, 1])
else:
if ttname == vdname and fflag:
continue
fflag = 0
testx.append(dd)
testy.append([0, 1])
ftotal -= 1
ttname = vdname
negdata = len(testy) - podata
#pdb.set_trace()
seed = random.randint(0, 100)
random.seed(seed)
random.shuffle(trainx)
random.seed(seed)
random.shuffle(trainy)
random.seed(seed)
random.shuffle(testx)
random.seed(seed)
random.shuffle(testy)
#pdb.set_trace()
trainx = np.array(trainx)
trainy = np.array(trainy)
trainx = trainx.reshape(-1, lstmnum, 100, 128, 3)
trainx = trainx.astype('float32')
testx = np.array(testx)
testx = testx.reshape(-1, lstmnum, 100, 128, 3)
testx = testx.astype('float32')
testy = np.array(testy)
#pdb.set_trace()
print(len(trainx))
print(len(testx))
print(podata, negdata)
modelname = sys.argv[3]
pdb.set_trace()
for case in switch(modelname):
if case('m0'):
model = createmodel.create_m0()
break
if case('m1'):
model = createmodel.create_m1()
break
if case('m2'):
model = createmodel.create_m2()
break
if case('m3'):
model = createmodel.create_m3()
break
if case('m4'):
model = createmodel.create_m4()
break
#model = createmodel.create_m0()
def auroc(y_true, y_pred):
return tf.py_func(metrics.roc_auc_score, (y_true, y_pred), tf.double)
model.compile(loss=categorical_crossentropy,
optimizer=Adadelta(),
metrics=['accuracy', auroc])
batch_size = 32
epochs = 60
# pdb.set_trace()
filepath = "weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True,
mode='max')
callbacks_list = [checkpoint]
modelweights = sys.argv[4]
#model = load_model('weights-improvement-27-0.79.hdf5')
model.load_weights(modelweights)
flat_layer = Model(model.input, outputs=model.get_layer('flatten_1').output)
test_out = flat_layer.predict(testx)
train_out = flat_layer.predict(trainx)
print(len(test_out))
pdb.set_trace()
trainyy = trainy[:, 0]
testyy = testy[:, 0]
import catboost as ctb
from catboost import CatBoostClassifier, CatBoostRegressor
metricname = 'AUC'
lossfunc = 'RMSE'
#model = CatBoostClassifier(iterations=10000, depth=3, bagging_temperature=0.2, l2_leaf_reg=50,
# custom_metric=metricname, learning_rate=0.5, eval_metric=metricname, loss_function=lossfunc,
# logging_level='Verbose')
model = CatBoostRegressor(iterations=10000, depth=3, bagging_temperature=0.2, l2_leaf_reg=50,
custom_metric=metricname, learning_rate=0.5, eval_metric=metricname, loss_function=lossfunc,
logging_level='Verbose')
model.fit(train_out, trainyy,eval_set=(test_out, testyy), plot=False)
pdb.set_trace()
predict = model.predict_proba(test_out)
np.save('predictcat', predict)
np.save('testcat', testyy)