-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleanganflowertest.py
241 lines (176 loc) · 6.16 KB
/
cleanganflowertest.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
# -*- coding: utf-8 -*-
"""CleanGANflowerTEST.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1chR10dy20tyR2XFrgFnYvm6MY9MIahl9
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import imageio
import numpy as np
import PIL
from tensorflow.keras import layers
import time
from IPython import display
from google.colab import files
from IPython.display import Image
import os
from tensorflow.python.framework import ops
ops.reset_default_graph()
pip install keras==2.2.4
!pip install tensorflow-gpu==1.13.1
!pip install kaggle
!apt install p7zip-full
!7z x daisies.zip
# Commented out IPython magic to ensure Python compatibility.
import os
from glob import glob
import cv2
from tensorflow.keras.layers import Input, Dense, Reshape, Flatten, Dropout
from tensorflow.keras.layers import BatchNormalization, Activation, ZeroPadding2D, UpSampling2D, Conv2D, LeakyReLU
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.optimizers import Adam
# %matplotlib inline
import matplotlib.pyplot as plt
PATH = os.path.abspath(os.path.join('..','/content', 'daisies'))
IMGS = glob(os.path.join(PATH, '*.jpg'))
print(len(IMGS)) # number of images
print(IMGS[:10]) # images filenames
WIDTH = 28
HEIGHT = 28
DEPTH = 3
def procImages(images):
processed_images = []
# set depth
depth = None
if DEPTH == 1:
depth = cv2.IMREAD_GRAYSCALE
elif DEPTH == 3:
depth = cv2.IMREAD_COLOR
else:
print('DEPTH must be set to 1 or to 3.')
return None
#resize images
for img in images:
base = os.path.basename(img)
full_size_image = cv2.imread(img, depth)
processed_images.append(cv2.resize(full_size_image, (WIDTH, HEIGHT), interpolation=cv2.INTER_CUBIC))
processed_images = np.asarray(processed_images)
# rescale images to [-1, 1]
processed_images = np.divide(processed_images, 127.5) - 1
return processed_images
processed_images = procImages(IMGS)
processed_images.shape
fig, axs = plt.subplots(3, 3)
count = 10
for i in range(3):
for j in range(3):
img = processed_images[count, :, :, :] * 127.5 + 127.5
img = np.asarray(img, dtype=np.uint8)
if DEPTH == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
axs[i, j].imshow(img)
axs[i, j].axis('off')
count += 1
plt.show()
# GAN parameters
LATENT_DIM = 100
G_LAYERS_DIM = [256, 512, 1024]
D_LAYERS_DIM = [1024, 512, 256]
BATCH_SIZE = 16
EPOCHS = 2000
LR = 0.0002
BETA_1 = 0.5
def buildGenerator(img_shape):
def addLayer(model, dim):
model.add(Dense(dim))
model.add(LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
model = Sequential()
model.add(tf.keras.layers.Dense(256, input_dim=100))
model.add(tf.keras.layers.LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
for layer_dim in G_LAYERS_DIM[1:]:
addLayer(model, layer_dim)
model.add(Dense(np.prod(img_shape), activation='tanh'))
model.add(Reshape(img_shape))
model.summary()
noise = Input(shape=(LATENT_DIM,))
img = model(noise)
return Model(noise, img)
def buildDiscriminator(img_shape):
def addLayer(model, dim):
model.add(Dense(dim))
model.add(LeakyReLU(alpha=0.2))
model = Sequential()
model.add(Flatten(input_shape=img_shape))
for layer_dim in D_LAYERS_DIM:
addLayer(model, layer_dim)
model.add(Dense(1, activation='sigmoid'))
model.summary()
img = Input(shape=img_shape)
classification = model(img)
return Model(img, classification)
def buildCombined(g, d):
# fix d for training g in the combined model
d.trainable = False
# g gets z as input and outputs fake_img
z = Input(shape=(LATENT_DIM,))
fake_img = g(z)
# gets the classification of the fake image
gan_output = d(fake_img)
# the combined model for training generator g to fool discriminator d
model = Model(z, gan_output)
model.summary()
return model
def sampleImages(generator):
rows, columns = 3, 3
noise = np.random.normal(0, 1, (rows * columns, LATENT_DIM))
generated_imgs = generator.predict(noise)
fig, axs = plt.subplots(rows, columns)
count = 0
for i in range(rows):
for j in range(columns):
img = generated_imgs[count, :, :, :] * 127.5 + 127.5
img = np.asarray(img, dtype=np.uint8)
if DEPTH == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
axs[i, j].imshow(img)
axs[i, j].axis('off')
count += 1
plt.show()
#instantiate the optimizer
optimizer = Adam(LR, BETA_1)
d = buildDiscriminator(processed_images.shape[1:])
d.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
#build generator
g = buildGenerator(processed_images.shape[1:])
g.compile(loss='binary_crossentropy', optimizer=optimizer)
#build combined model
c = buildCombined(g, d)
c.compile(loss='binary_crossentropy', optimizer=optimizer)
SAMPLE_INTERVAL = WARNING_INTERVAL = 100
YDis = np.zeros(2 * BATCH_SIZE)
YDis[:BATCH_SIZE] = .9 #Label smoothing
YGen = np.ones(BATCH_SIZE)
for epoch in range(EPOCHS):
# get a batch of real images
idx = np.random.randint(0, processed_images.shape[0], BATCH_SIZE)
real_imgs = processed_images[idx]
# generate a batch of fake images
noise = np.random.normal(0, 1, (BATCH_SIZE, LATENT_DIM))
fake_imgs = g.predict(noise)
X = np.concatenate([real_imgs, fake_imgs])
# Train discriminator
d.trainable = True
d_loss = d.train_on_batch(X, YDis)
# Train the generator
d.trainable = False
#noise = np.random.normal(0, 1, (BATCH_SIZE, LATENT_DIM))
g_loss = c.train_on_batch(noise, YGen)
# Progress
if (epoch+1) % WARNING_INTERVAL == 0 or epoch == 0:
print ("%d [Discriminator Loss: %f, Acc.: %.2f%%] [Generator Loss: %f]" % (epoch, d_loss[0], 100. * d_loss[1], g_loss))
# If at save interval => save generated image samples
if (epoch+1) % SAMPLE_INTERVAL == 0 or epoch == 0:
sampleImages(g)