-
Notifications
You must be signed in to change notification settings - Fork 676
/
GAN Generative Adversarial 3
251 lines (205 loc) · 8.04 KB
/
GAN Generative Adversarial 3
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
import keras
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from keras.layers import Input, Dense, Lambda
from keras.models import Model
from keras import backend as K
from keras import objectives
from keras.datasets import mnist
from keras.layers.core import Reshape
from __future__ import print_function
import numpy as np
np.random.seed(1337)
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D, UpSampling2D
from keras.utils import np_utils
from keras import backend as K
from keras.layers.normalization import BatchNormalization
from keras.callbacks import ModelCheckpoint,LearningRateScheduler
import os
os.environ["KERAS_BACKEND"] = "theano"
#os.environ["THEANO_FLAGS"] = "device=gpu%d,lib.cnmem=0"%(random.randint(0,3))
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))
x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))
x_train=x_train[1:2]
x_test=x_test[1:2]
y_train=y_train[1:2]
y_test=y_test[1:2]
batch_size = 1
nb_classes = 10
nb_epoch = 1
# input image dimensions
img_rows, img_cols = 28, 28
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = (2, 2)
# convolution kernel size
kernel_size = (3, 3)
# the data, shuffled and split between train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()
if K.image_dim_ordering() == 'th':
X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows,img_cols)
else:
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)
X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
X_train = X_train.astype('float32')[1:2]
X_test = X_test.astype('float32')[1:2]
X_train /= 255
X_test /= 255
print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')
sd=[]
class LossHistory(keras.callbacks.Callback):
def on_train_begin(self, logs={}):
self.losses = [1,1]
def on_epoch_end(self, batch, logs={}):
self.losses.append(logs.get('loss'))
sd.append(step_decay(len(self.losses)))
print('learning rate:', step_decay(len(self.losses)))
print('derivative of loss:', 2*np.sqrt((self.losses[-1])))
def my_init(shape, name=None):
value = np.random.random(shape)
return K.variable(value, name=name)
def step_decay(losses):
if float(2*np.sqrt(np.array(history.losses[-1])))<1.6:
lrate=0.006
momentum=0.4
decay_rate=0.0
return lrate
else:
lrate=0.01
return lrate
generator = Sequential()
generator.add(Convolution2D(20, 3,3,
border_mode='valid',
input_shape=input_shape))
generator.add(BatchNormalization(mode=2))
generator.add(Activation('relu'))
generator.add(UpSampling2D(size=(2, 2)))
generator.add(Convolution2D(20, 3, 3,
init='glorot_uniform'))
generator.add(BatchNormalization(mode=2))
generator.add(Activation('relu'))
generator.add(Convolution2D(20, 3, 3,init='glorot_uniform'))
generator.add(BatchNormalization(mode=2))
generator.add(Activation('relu'))
generator.add(MaxPooling2D(pool_size=(3,3)))
generator.add(Convolution2D(4, 3, 3,init='glorot_uniform'))
generator.add(BatchNormalization(mode=2))
generator.add(Activation('relu'))
generator.add(Reshape((28,28,1)))
generator.compile(loss='binary_crossentropy', optimizer='adam')
generator.summary()
############# DISCRIMINATOR
# the data, shuffled and split between train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()
if K.image_dim_ordering() == 'th':
X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows,img_cols)
else:
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)
X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
X_train = X_train.astype('float32')[1:2]
X_test = X_test.astype('float32')[1:2]
X_train /= 255
X_test /= 255
print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, nb_classes)[1:2]
Y_test = np_utils.to_categorical(y_test, nb_classes)[1:2]
history=LossHistory()
lrate=LearningRateScheduler(step_decay)
discriminator = Sequential()
discriminator.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
border_mode='valid',
input_shape=input_shape))
discriminator.add(Activation('relu'))
discriminator.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))
discriminator.add(Activation('relu'))
discriminator.add(MaxPooling2D(pool_size=pool_size))
discriminator.add(Dropout(0.25))
discriminator.add(Flatten())
discriminator.add(Dense(64))
discriminator.add(Activation('relu'))
discriminator.add(Dropout(0.5))
discriminator.add(Dense(nb_classes))
discriminator.add(Activation('sigmoid'))
discriminator.compile(loss='categorical_crossentropy',
optimizer='adadelta',
metrics=['accuracy'])
filepath="CNN_MNIST-{loss:.4f}.hdf5"
checkpoint_discr = ModelCheckpoint(filepath, monitor='binary_crossentropy', verbose=1, save_best_only=True)
discriminator.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=1,callbacks=[history,lrate,checkpoint_discr],
verbose=1, validation_data=(X_test, Y_test))
score = discriminator.evaluate(X_test, Y_test, verbose=2)
print('Test score:', score[0])
print('Test accuracy:', score[1])
def not_train(net, val):
net.trainable = val
for k in net.layers:
k.trainable = val
not_train(discriminator, False)
gan_input = Input(batch_shape=(1, 28,28,1))
generator.summary()
discriminator.summary()
gan_level2 = discriminator(generator(gan_input))
GAN = Model(gan_input, gan_level2)
GAN.compile(loss='categorical_crossentropy', optimizer='adam')
filepath="CNN_STACKED-{loss:.4f}.hdf5"
checkpoint_stacked = ModelCheckpoint(filepath, monitor='binary_crossentropy', verbose=1, save_best_only=False)
GAN.fit(x_train.reshape((1,28,28,1)), Y_train.reshape((1,10)), batch_size=batch_size, nb_epoch=2,
verbose=1,callbacks=[history,lrate,checkpoint_stacked])
filename = "CNN_STACKED-2.2547.hdf5"
GAN.load_weights(filename)
GAN.compile(loss='binary_crossentropy', optimizer='adam')
bb=GAN.predict(x_test.reshape((1,28,28,1)))
c=np.where(bb[0]==np.max(bb))[0]
Y_train[0][c]
### YESSSS
noise = np.random.uniform(0,1,size=[1,784]).reshape((1,28,28,1))
generated_images = generator.predict(noise)
plt.imshow(generated_images.reshape((28,28)),cmap='Greys')
plt.imshow(X_train.reshape((28,28)),cmap='Greys')
GAN.get_config()
GAN.summary()
GAN.get_weights()
from __future__ import print_function
import h5py
def print_structure(weight_file_path):
f = h5py.File(weight_file_path)
try:
if len(f.attrs.items()):
print("{} contains: ".format(weight_file_path))
print("Root attributes:")
for key, value in f.attrs.items():
print(" {}: {}".format(key, value))
if len(f.items())==0:
return
for layer, g in f.items():
print(" {}".format(layer))
print(" Attributes:")
for key, value in g.attrs.items():
print(" {}: {}".format(key, value))
print(" Dataset:")
for p_name in g.keys():
param = g[p_name]
print(" {}: {}".format(p_name, np.array(param).shape))
finally:
f.close()
print_structure('CNN_STACKED-2.2547.hdf5')