La Praktikum m3
La Praktikum m3
In [6]:
import numpy as np
!mkdir generated_images
img_width = 28
img_height = 28
channels = 1
img_shape = (img_width, img_height, channels)
latent_dim = 100
adam = Adam(lr=0.0001)
/usr/local/lib/python3.7/dist-packages/keras/optimizers/optimizer_v2/adam.py:110: UserWarn
ing: The `lr` argument is deprecated, use `learning_rate` instead.
super(Adam, self).__init__(name, **kwargs)
3) Building Generator
In [8]:
def build_generator():
model = Sequential()
model.add(Dense(256, input_dim=latent_dim))
model.add(LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
model.add(Dense(256))
model.add(LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
model.add(Dense(256))
model.add(LeakyReLU(alpha=0.2))
model.add(BatchNormalization(momentum=0.8))
model.add(Dense(np.prod(img_shape), activation='tanh'))
model.add(Reshape(img_shape))
model.summary()
return model
generator = build_generator()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 256) 25856
=================================================================
Total params: 362,000
Trainable params: 360,464
Non-trainable params: 1,536
_________________________________________________________________
4) Building Discriminator
In [9]:
def build_discriminator():
model = Sequential()
model.add(Flatten(input_shape=img_shape))
model.add(Dense(512))
model.add(LeakyReLU(alpha=0.2))
model.add(Dense(256))
model.add(Dense(1, activation='sigmoid'))
model.summary()
return model
discriminator = build_discriminator()
discriminator.compile(loss='binary_crossentropy', optimizer=adam, metrics=['accuracy'])
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
flatten (Flatten) (None, 784) 0
=================================================================
Total params: 533,505
Trainable params: 533,505
Non-trainable params: 0
_________________________________________________________________
GAN.compile(loss='binary_crossentropy', optimizer=adam)
GAN.summary()
Model: "sequential_2"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
sequential (Sequential) (None, 28, 28, 1) 362000
=================================================================
Total params: 895,505
Trainable params: 360,464
Non-trainable params: 535,041
_________________________________________________________________
6) Outputting Images
In [11]:
#@title
## **7) Outputting Images**
import matplotlib.pyplot as plt
import glob
import imageio
import PIL
save_name = 0.00000000
def save_imgs(epoch):
r, c = 5, 5
noise = np.random.normal(0, 1, (r * c, latent_dim))
gen_imgs = generator.predict(noise)
global save_name
save_name += 0.00000001
print("%.8f" % save_name)
# Rescale images 0 - 1
gen_imgs = 0.5 * gen_imgs + 0.5
7) Training GAN
In [12]:
def train(epochs, batch_size=64, save_interval=200):
(X_train, _), (_, _) = mnist.load_data()
# print(X_train.shape)
#Rescale data between -1 and 1
X_train = X_train / 127.5 -1.
# X_train = np.expand_dims(X_train, axis=3)
# print(X_train.shape)
#Train discriminator
d_loss_real = discriminator.train_on_batch(imgs, valid)
d_loss_fake = discriminator.train_on_batch(gen_imgs, fakes)
d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
#inverse y label
g_loss = GAN.train_on_batch(noise, valid)
if (epoch % save_interval) == 0:
save_imgs(epoch)
# print(valid)
8) Making GIF
In [13]:
# Display a single image using the epoch number
# def display_image(epoch_no):
# return PIL.Image.open('generated_images/%.8f.png'.format(epoch_no))
anim_file = 'dcgan.gif'
In [13]: