-
Notifications
You must be signed in to change notification settings - Fork 1
/
model_build.py
419 lines (368 loc) · 15.2 KB
/
model_build.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import warnings
# Don't fear the future
warnings.simplefilter(action='ignore', category=FutureWarning)
# load all the layers
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import Bidirectional
from tensorflow.keras.layers import Concatenate
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import GRU
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import LeakyReLU
from tensorflow.keras.layers import MaxPool2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Permute
from tensorflow.keras.layers import Reshape
from tensorflow.keras.layers import TimeDistributed
from tensorflow.keras.layers import UpSampling2D
from tensorflow.keras.layers import ZeroPadding2D
# load model
from tensorflow.keras import Model
from tensorflow.keras.models import Sequential, load_model, Model
# load back end
from tensorflow.keras import backend
# load optimizers
from tensorflow.keras.optimizers import Adam
# load other tensor stuff
import tensorflow as tf
# load other stuff stuff
import os
import numpy as np
def noise_enc():
ne = None
return ne
###Rory code
def context_enc():
# one aproch
# https://towardsdatascience.com/an-approach-towards-convolutional-recurrent-neural-networks-f54cbeecd4a6
# vary setings
shape_in = int(320), int(8), int(1)
shape_out = int(8134), int(120)
dropoutrate = 0.3
x_start = Input(shape=(shape_in))
x = x_start
for _i, _cnt in enumerate((2, 2)):
x = Conv2D(filters = 100, kernel_size=(2, 2), padding='same',)(x)
x = BatchNormalization(axis=-1)(x)
#x = Activation('relu')(x)
x = LeakyReLU()(x)
#x = MaxPooling2D(pool_size=(2,2), dim_ordering="th" )(x)
x = MaxPooling2D(pool_size=2)(x)
x = Dropout(dropoutrate)(x)
x = Permute((2, 1, 3))(x)
x = Reshape((1, 16000))(x)
# The Gru/recurrent portion
# Get some knowledge
# http://colah.github.io/posts/2015-08-Understanding-LSTMs/
for r in (10,10):
x = Bidirectional(
GRU(r,
activation='tanh',
dropout=dropoutrate,
recurrent_dropout=dropoutrate,
return_sequences=True),
merge_mode='concat')(x)
for f in ((2,2)):
x = TimeDistributed(Dense(f))(x)
x = Dropout(dropoutrate)(x)
x = TimeDistributed(Dense(880))(x)
# arbitrary reshape may be a problem
x = Reshape((22,40,1))(x)
out = Activation('sigmoid', name='strong_out')(x)
#audio_context = Model(inputs=x_start, outputs=out)
#audio_context.compile(optimizer='Adam', loss='binary_crossentropy',metrics = ['accuracy'])
#audio_context.summary()
ce = out
#ce = audio_context
return ce, x_start
#UNET Functions
def down_block(x, filters, kernal_size = (3, 3), padding ='same', strides=1):
c= Conv2D(filters, kernal_size, padding=padding, strides=strides, activation='relu')(x)
c= Conv2D(filters, kernal_size, padding=padding, strides=strides, activation='relu')(c)
p = MaxPool2D((2, 2), (2, 2))(c)
return c, p
def up_block(x, skip, filters, kernal_size =(3, 3), padding='same', strides= 1):
us = UpSampling2D((2, 2))(x)
concat = Concatenate()([us, skip])
c= Conv2D(filters, kernal_size, padding=padding, strides=strides, activation='relu')(concat)
c= Conv2D(filters, kernal_size, padding=padding, strides=strides, activation='relu')(c)
return c
def up_block1(x, skip, filters, kernal_size =(3, 3), padding='same', strides= 1):
us = UpSampling2D((2, 2))(x)
concat = Concatenate()([x, skip])
c= Conv2D(filters, kernal_size, padding=padding, strides=strides, activation='relu')(concat)
c= Conv2D(filters, kernal_size, padding=padding, strides=strides, activation='relu')(c)
return c
def bottleneck(IE, AE, NE, filters, kernal_size = (3, 3), padding ='same', strides=1):
#join_shape = (22,40, 128)
join_shape = (4, 8, 128)
IE = Flatten()(IE)
AE = Flatten()(AE)
concat1 = Concatenate()([IE, AE])
concat1 = Dense(np.prod(join_shape))(concat1)
concat1 = Reshape(join_shape)(concat1)
c= Conv2D(filters, kernal_size, padding=padding, strides=strides, activation='relu')(concat1)
c= Conv2D(filters, kernal_size, padding=padding, strides=strides, activation='relu')(c)
return c
#def Gener(input_dim, image_channels):
#def build_generator(discrim):
def build_generator():
f= [8, 16, 32, 64, 128, 256]
#Filters per layers
#Data shape entering the convolusion
inputs = Input((64,128,3))
#Input layer
p0= inputs
#Down bloc encoding
c1, p1 = down_block(p0, f[0])
c2, p2 = down_block(p1, f[1])
c3, p3 = down_block(p2, f[2])
c4, p4 = down_block(p3, f[3])
c5, p5 = down_block(p4, f[4]) # output is 4,8, 128
# test = Model(inputs=inputs, outputs=p5)
# test.compile(optimizer='Adam', loss='binary_crossentropy',metrics = ['accuracy'])
# test.summary()
#switch over layer to up bloc decoder
ne = noise_enc()
ae, inputs2 = context_enc()
bn = bottleneck(p5, ae, ne, f[5])
#Up bloc decoding
u1 = up_block1(bn, c5, f[4])
u2 = up_block(u1, c4, f[3])
u3 = up_block(u2, c3, f[2])
u4 = up_block(u3, c2, f[1])
u5 = up_block(u4, c1, f[0])
#autoencoder egress layer. Flatten and any perceptron layers would succeed this layer
outputs = Conv2D(3, (1, 1), padding='same', activation = 'tanh')(u5)
#outputs = Conv2D(3, (1, 1), padding='same', activation = 'tanh')(bn)
#Keras model output
model = Model([inputs, inputs2], outputs, name='gener')
#model.compile(optimizer='Adam', loss='binary_crossentropy',metrics = ['accuracy'])
return model, [inputs, inputs2]
def build_discriminator():
# one aproch
# https://towardsdatascience.com/an-approach-towards-convolutional-recurrent-neural-networks-f54cbeecd4a6
# vary settings
shape_in_x = int(320), int(8), int(1)
shape_in_y = int(64), int(128), int(3)
#shape_out = int(8134), int(120)
dropoutrate = 0.3
x_start = Input(shape=(shape_in_x))
x = x_start
for _i, _cnt in enumerate((2, 2)):
x = Conv2D(filters = 100, kernel_size=(2, 2), padding='same',)(x)
x = BatchNormalization(axis=-1)(x)
#x = Activation('relu')(x)
x = LeakyReLU()(x)
#x = MaxPooling2D(pool_size=(2,2), dim_ordering="th" )(x)
x = MaxPooling2D(pool_size=2)(x)
x = Dropout(dropoutrate)(x)
x = Flatten()(x) # shape out = none 16000
#out = Activation('sigmoid', name='strong_out')(x)
#audio_context = Model(inputs=x_start, outputs=out)
#audio_context.compile(optimizer='Adam', loss='binary_crossentropy',metrics = ['accuracy'])
#audio_context.summary()
y_start = Input(shape=(shape_in_y))
y = y_start
for _i, _cnt in enumerate((2, 2)):
y = Conv2D(filters = 100, kernel_size=(2, 2), padding='same',)(y)
y = BatchNormalization(axis=-1)(y)
#y = Activation('relu')(y)
y = LeakyReLU()(y)
#y = MayPooling2D(pool_size=(2,2), dim_ordering="th" )(y)
y = MaxPooling2D(pool_size=2)(y)
y = Dropout(dropoutrate)(y)
y = Flatten()(y)
#out = Activation('sigmoid', name='strong_out')(y)
#audio_context = Model(inputs=y_start, outputs=out)
#audio_context.compile(optimizer='Adam', loss='binary_crossentropy',metrics = ['accuracy'])
#audio_context.summary()# (None, 51200)
z = Concatenate()([y, x])
#z = Reshape((-1, 1))(z) # Why dose this not work?
z = Reshape((67200, 1))(z)
#out = Activation('sigmoid', name='strong_out')(z)
#audio_context = Model(inputs=[x_start,y_start], outputs=out)
#audio_context.compile(optimizer='Adam', loss='binary_crossentropy',metrics = ['accuracy'])
#audio_context.summary() # (None, 67200)
# The Gru/recurrent portion
# Get some knowledge
# http://colah.github.io/posts/2015-08-Understanding-LSTMs/
for r in (10,10):
z = Bidirectional(
GRU(r,
activation='tanh',
dropout=dropoutrate,
recurrent_dropout=dropoutrate,
return_sequences=True),
merge_mode='concat')(z)
for f in ((2,2)):
z = TimeDistributed(Dense(f))(z)
#z = Dropout(dropoutrate)(z)
#z = TimeDistributed(Dense(880))(z)
# arbitrary reshape may be a problem
z = Flatten()(z)
z = Dropout(dropoutrate)(z)
z = Dense(1,activation = 'sigmoid')(z)
#out = Activation('sigmoid', name='strong_out')(z)
descrim = Model(inputs=[y_start, x_start], outputs=z)
descrim.compile(optimizer='Adam', loss='binary_crossentropy',metrics = ['accuracy'])
#descrim.summary()
#ce = audio_context
return descrim, x_start
def build_frame_discriminator():
# one aproch
# https://towardsdatascience.com/an-approach-towards-convolutional-recurrent-neural-networks-f54cbeecd4a6
# vary settings
shape_in_x = int(64), int(128), int(3)
#shape_out = int(8134), int(120)
dropoutrate = 0.3
x_start = Input(shape=(shape_in_x))
x1_start = Input(shape=(shape_in_x))
x = x_start
for _i, _cnt in enumerate((2, 2)):
x = Conv2D(filters = 100, kernel_size=(2, 2), padding='same',)(x)
x = BatchNormalization(axis=-1)(x)
#x = Activation('relu')(x)
x = LeakyReLU()(x)
#x = MaxPooling2D(pool_size=(2,2), dim_ordering="th" )(x)
x = MaxPooling2D(pool_size=2)(x)
x = Dropout(dropoutrate)(x)
x = Flatten()(x) # shape out = none 16000
#out = Activation('sigmoid', name='strong_out')(x)
#audio_context = Model(inputs=x_start, outputs=out)
#audio_context.compile(optimizer='Adam', loss='binary_crossentropy',metrics = ['accuracy'])
#audio_context.summary()
# I don't think we need y
#y_start = Input(shape=(shape_in_y))
#y = y_start
#for _i, _cnt in enumerate((2, 2)):
# y = Conv2D(filters = 100, kernel_size=(2, 2), padding='same',)(y)
# y = BatchNormalization(axis=-1)(y)
# #y = Activation('relu')(y)
# y = LeakyReLU()(y)
# #y = MayPooling2D(pool_size=(2,2), dim_ordering="th" )(y)
# y = MaxPooling2D(pool_size=2)(y)
# y = Dropout(dropoutrate)(y)
#y = Flatten()(y)
#out = Activation('sigmoid', name='strong_out')(y)
#audio_context = Model(inputs=y_start, outputs=out)
#audio_context.compile(optimizer='Adam', loss='binary_crossentropy',metrics = ['accuracy'])
#audio_context.summary()# (None, 51200)
# z is duplicate picture input
z = Concatenate()([x, x])
#z = Reshape((-1, 1))(z) # Why dose this not work?
#z = Reshape((67200, 1))(z)
#out = Activation('sigmoid', name='strong_out')(z)
#audio_context = Model(inputs=[x_start,y_start], outputs=out)
#audio_context.compile(optimizer='Adam', loss='binary_crossentropy',metrics = ['accuracy'])
#audio_context.summary() # (None, 67200)
# The Gru/recurrent portion
# Get some knowledge
# http://colah.github.io/posts/2015-08-Understanding-LSTMs/
#for r in (10,10):
# z = Bidirectional(
# GRU(r,
# activation='tanh',
# dropout=dropoutrate,
# recurrent_dropout=dropoutrate,
# return_sequences=True),
# merge_mode='concat')(z)
# for f in ((2,2)):
# z = TimeDistributed(Dense(f))(z)
#z = Dropout(dropoutrate)(z)
#z = TimeDistributed(Dense(880))(z)
# arbitrary reshape may be a problem
#z = Flatten()(z)
z = Dropout(dropoutrate)(z)
z = Dense(1000,activation = 'sigmoid')(z)
z = Dense(100,activation = 'sigmoid')(z)
z = Dense(1,activation = 'sigmoid')(z)
#out = Activation('sigmoid', name='strong_out')(z)
descrim = Model(inputs=[x1_start, x_start], outputs=z)
descrim.compile(optimizer='Adam', loss='binary_crossentropy',metrics = ['accuracy'])
#descrim.summary()
#ce = audio_context
return descrim, x_start
# discriminator, aud_input = build_discriminator()
# #discriminator.summary()
# generator, inputs = build_generator()
# gd_joint = generator(inputs)
#
# # For the combined model we will only train the generator
# discriminator.trainable = False
#
# # The discriminator takes generated images as input and determines validity
# validity = discriminator([gd_joint, aud_input])
#
# # The combined model (stacked generator and discriminator)
# # Trains the generator to fool the discriminator
# inputs.append(aud_input)
# combination = Model(inputs, validity)
# combination.compile(loss='binary_crossentropy', optimizer=Adam(0.0002, 0.5))
#
#
# # Because of time needed, we use a Numpy preprocessed file.
# training_vid_path = "/home/dl-group/data/Video/video1.npy"
# training_audio_path = "/home/dl-group/data/Audio/audio1.npy"
#
# print("Loading training data.")
# training_vid = np.load(training_vid_path)
# training_aud = np.load(training_audio_path)
# # take the first video and make a matrix used as part of generator context
# first_vid = np.zeros(training_vid.shape, dtype='float16')
# for i in range(first_vid.shape[0]):
# first_vid[i,:,:,:] = training_vid[0,:,:,:]
#
# training_vid.shape
# training_aud.shape
#
# #
# # Training block
# #
#
#
# cnt = 1
# num_epoch = 200
# num_epoch = 1
# batch_size = 10
# batch_size = 1
# seed_size = 42
# work_path = './'
# save_freq = 10
# save_freq = 1
# metrics = []
#
# for epoch in range(num_epoch):
# idi = np.random.randint(0, training_vid.shape[0]-batch_size)
# idx = list(range(idi, idi + batch_size))
# x_real_vid = training_vid[idx]
# x_real_aud = training_aud[idx]
# image_context = first_vid[idx]
# # Generate some images
# # seed = np.random.normal(0,1,(batch_size,seed_size))
# x_fake_vid = generator.predict([image_context, x_real_aud])
# y_real = np.ones((batch_size))
# y_fake = np.zeros((batch_size))
# # Train discriminator on real and fake
# discriminator_metric_real = discriminator.train_on_batch([x_real_vid, x_real_aud], y_real)
# discriminator_metric_generated = discriminator.train_on_batch([x_fake_vid, x_real_aud], y_fake)
# discriminator_metric = 0.5 * np.add(discriminator_metric_real,discriminator_metric_generated)
# # Train generator on Calculate losses
# # y_pred = discriminator.predict([x_real_aud, x_fake_vid])
# generator_metric = combination.train_on_batch([image_context, x_real_aud, x_real_aud], y_real)
# metrics.append([discriminator_metric, generator_metric])
# # Time for an update?
# # if epoch % save_freq == 0:
# # save_images(cnt, fixed_seed)
# # cnt += 1
# # if epoch % save_freq == 0: print(f"Epoch {epoch}, Discriminator accuarcy: {discriminator_metric[1]}, Generator accuracy: {generator_metric[1]}")
# if epoch > 1 and epoch % save_freq == 0:
# generator.save(os.path.join(work_path,"generator-e{}.h5".format(epoch)))
# discriminator.save(os.path.join(work_path,"discriminator-e{}.h5".format(epoch)))
#
# import pandas as pd
# pd.DataFrame(np.asmatrix([[m[0][0] for m in metrics], [m[0][1] for m in metrics], [m[1] for m in metrics]]).T)