# python ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ
import os
import time
import glob
# ์คํ์์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ
import tensorflow as tf
from tensorflow.keras import layers
import imageio # ์์ฑ ๋ฐ์ดํฐ๋ฅผ GIFํํ๋ก ๋ง๋ค์ด์ฃผ๊ธฐ ์ํ ๊ฒ
import matplotlib.pyplot as plt
import numpy as np
import PIL
# ๋ชจ๋ ์ด๋ฏธ์ง๋ฅผ ํ์ํ๊ธฐ ์ํด IPython ๋ชจ๋์ ํด๋์ค๋ฅผ ์ฌ์ฉ
from IPython import display
os
์ด์์ฒด์ ์์ ์ ๊ณต๋๋ ์ฌ๋ฌ๊ธฐ๋ฅ(๊ฒฝ๋ก ๊ฐ์ ธ์ค๊ธฐ, ํด๋ ์์ฑ, ํด๋ ๋ด ํ์ผ ๋ชฉ๋ก ๊ตฌํ๊ธฐ ๋ฑ)์ ํ์ด์ฌ์์ ์ฌ์ฉํ ์ ์๋๋ก ํ๋ ๋ชจ๋
glob
(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()
train_images์ shape๋ (60000, 28, 28)์ผ๋ก ์ด 6๋ง๊ฐ์ 28 x 28 ํด์๋ ์ด๋ฏธ์ง๊ฐ ์ ์ฅ๋์ด ์๋ค.
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
train_images = (train_images - 127.5) / 127.5 # ์ด๋ฏธ์ง๋ฅผ [-1, 1]๋ก ์ ๊ทํํฉ๋๋ค.
reshape
๋ํ์ด ๋ฐฐ์ด์ ์ฐจ์์ ๋ณํํ๋ค.
astype
๋ฐ์ดํฐ ํ๋ ์ ๋ด ๋ฐ์ดํฐ๋ค์ ๋ฐ์ดํฐ ํ์
์ ๋ณ๊ฒฝ
BUFFER_SIZE = 60000
BATCH_SIZE = 256
# ๋ฐ์ดํฐ ๋ฐฐ์น๋ฅผ ๋ง๋ค๊ณ ์์ต๋๋ค.
train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
tf.data.Dataset.from_tensor_slices
shuffle
batch
๋ฐ์ดํฐ์
์ ํญ๋ชฉ๋ค์ ํ๋์ ๋ฐฐ์น๋ก ๋ฌถ์ด์ค๋ค.
def make_generator_model():
model = tf.keras.Sequential()
model.add(layers.Dense(128, activation='relu', input_shape=(100,)))
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(28*28*1, activation='tanh'))
model.add(layers.Reshape((28, 28, 1)))
return model
์์ฑ์ ๋ชจ๋ธ์ ๊ตฌ์กฐ๋ฅผ ๊ทธ๋ฆผ์ผ๋ก ๋ํ๋ด๋ฉด ์๋์ ๊ฐ๋ค.
def make_discriminator_model():
model = tf.keras.Sequential()
model.add(layers.Flatten())
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dense(128, activation='relu'))
model.add(layers.Dense(1))
return model
ํ๋ณ์ ๋ชจ๋ธ์ ๊ตฌ์กฐ๋ฅผ ๊ทธ๋ฆผ์ผ๋ก ๋ํ๋ด๋ฉด ์๋์ ๊ฐ๋ค.
generator = make_generator_model()
discriminator = make_discriminator_model()
# ์์คํจ์ ์ ์
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
# ์์ฑ์ ์์คํจ์
# fake image๋ฅผ ๋ฃ์์ ๋ 1์ด ๋์ค๋๋ก ํ์ต
def generator_loss(fake_output):
return cross_entropy(tf.ones_like(fake_output), fake_output)
Generator์ loss๋ ์์ฑํ fake image๋ฅผ Discriminator๊ฐ ํ๋ณํ ๊ฒฐ๊ณผ๊ฐ์ธ fake_output์ ๋ฐ์์, ๊ทธ ๊ฐ์ด 1์์ ์ผ๋ง๋ ๋ฉ๋ฆฌ์๋๊ฐ๋ฅผ ๊ธฐ์ค์ผ๋ก Loss๋ฅผ ๊ฒฐ์ ํ๋ค.
tf.ones_like
ํน์ tensor์ ๋น์ทํ๋ฉด์ ๋ชจ๋ element๊ฐ 1์ธ tensor๋ฅผ ๋ง๋ค์ด์ค๋ค.
# ํ๋ณ์ ์์คํจ์
# real image๋ฅผ ๋ฃ์ผ๋ฉด 1, fake image๋ฅผ ๋ฃ์ผ๋ฉด 0์ด ๋์ค๊ฒ ํ์ต
def discriminator_loss(real_output, fake_output):
real_loss = cross_entropy(tf.ones_like(real_output), real_output)
fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)
total_loss = real_loss + fake_loss
return total_loss
์ ๋ ๊ฐ์ Loss๋ฅผ ๊ฐ๊ฐ ๊ณ์ฐํ๊ณ , ํฉ์น ๊ฐ์ Discriminator์ loss๋ก ๋ฐํํ๋ค.
tf.zeos_like
ํน์ tensor์ ๋น์ทํ๋ฉด์ ๋ชจ๋ element๊ฐ 0์ธ tensor๋ฅผ ๋ง๋ค์ด์ค๋ค.
# Optimizer ์ ์
generator_optimizer = tf.keras.optimizers.Adam(1e-4)
discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
EPOCHS = 300
noise_dim = 100
num_examples_to_generate = 16
# ์ด ์๋๋ฅผ ์๊ฐ์ด ์ง๋๋ ์ฌํ์ฉํ๊ฒ ์ต๋๋ค.
# (GIF ์ ๋๋ฉ์ด์
์์ ์ง์ ๋ด์ฉ์ ์๊ฐํํ๋๋ฐ ์ฝ๊ธฐ ๋๋ฌธ์
๋๋ค.)
seed = tf.random.normal([num_examples_to_generate, noise_dim])
noise_dim
Generator์ Input์ผ๋ก ์ฌ์ฉ ๋ Latant Vector์ ํฌ๊ธฐ๋ฅผ 100์ผ๋ก ์ ์ํ๋ค.
num_examples_to_generator
ํ๋ จ๊ณผ์ ์์ Generator๊ฐ ์์ฑํ๋ ์ด๋ฏธ์ง๋ฅผ ๋ช ๊ฐ์ฉ ํ์ธ ํ ์ง ์ ์ํ๋ ๋ณ์
seed
# `tf.function`์ด ์ด๋ป๊ฒ ์ฌ์ฉ๋๋์ง ์ฃผ๋ชฉํด ์ฃผ์ธ์.
# ์ด ๋ฐ์ฝ๋ ์ดํฐ๋ ํจ์๋ฅผ "์ปดํ์ผ"ํฉ๋๋ค.
@tf.function
def train_step(images):
noise = tf.random.normal([BATCH_SIZE, noise_dim])
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
# generator์ noise ๋ฃ๊ณ fake image ์์ฑ
generated_images = generator(noise, training=True)
# discriminator์ real image์ fake image ๋ฃ๊ณ ํ๋ณ๊ฐ ๋ฆฌํด
real_output = discriminator(images, training=True)
fake_output = discriminator(generated_images, training=True)
# fake image๋ฅผ discriminator๊ฐ 1๋ก ํ์ต ํ๋๋ก ์
๋ฐ์ดํธ
gen_loss = generator_loss(fake_output)
# real image loss์ fake image loss ํฉํ total loss ๋ฆฌํด
disc_loss = discriminator_loss(real_output, fake_output)
# gen_tape.gradient(y, x) ํจ์๋ก ๋ฏธ๋ถ ๊ฐ(๊ธฐ์ธ๊ธฐ)์ ๊ตฌํจ
gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
# ๊ฐ์ค์น ์
๋ฐ์ดํธ
generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))
discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))
@tf.function ๋ฐ์ฝ๋ ์ดํฐ
tf.GradientTape()
์คํ๋ ๋ชจ๋ ์ฐ์ฐ์ tape์ ๊ธฐ๋กํ ํ ์๋ ๋ฏธ๋ถ์ ์ฌ์ฉํด tape์ ๊ธฐ๋ก๋ ์ฐ์ฐ์ ๊ทธ๋๋์ธํธ๋ฅผ ๊ณ์ฐํ๋ค.
def train(dataset, epochs):
for epoch in range(epochs):
start = time.time()
for image_batch in dataset:
train_step(image_batch)
# GIF๋ฅผ ์ํ ์ด๋ฏธ์ง๋ฅผ ๋ฐ๋ก ์์ฑํฉ๋๋ค.
display.clear_output(wait=True)
generate_and_save_images(generator,
epoch + 1,
seed)
# print (' ์ํฌํฌ {} ์์ ๊ฑธ๋ฆฐ ์๊ฐ์ {} ์ด ์
๋๋ค'.format(epoch +1, time.time()-start))
print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))
# ๋ง์ง๋ง ์ํฌํฌ๊ฐ ๋๋ ํ ์์ฑํฉ๋๋ค.
display.clear_output(wait=True)
generate_and_save_images(generator,
epochs,
seed)
def generate_and_save_images(model, epoch, test_input):
# `training`์ด False๋ก ๋ง์ถฐ์ง ๊ฒ์ ์ฃผ๋ชฉํ์ธ์.
# ์ด๋ ๊ฒ ํ๋ฉด (๋ฐฐ์น์ ๊ทํ๋ฅผ ํฌํจํ์ฌ) ๋ชจ๋ ์ธต๋ค์ด ์ถ๋ก ๋ชจ๋๋ก ์คํ๋ฉ๋๋ค.
predictions = model(test_input, training=False)
fig = plt.figure(figsize=(4,4))
for i in range(predictions.shape[0]):
plt.subplot(4, 4, i+1)
plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')
plt.axis('off')
plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))
plt.show()
%%time
train(train_dataset, EPOCHS)
๋งค epoch ๋ง๋ค Generator๊ฐ ์์ฑํ๋ ์ด๋ฏธ์ง์ ์๊ฐ์ ํ์ธ ํ ์ ์๋ค.
# gif ์์ฑ
anim_file = 'gan.gif'
with imageio.get_writer(anim_file, mode='I') as writer:
filenames = glob.glob('image*.png')
filenames = sorted(filenames)
last = -1
for i,filename in enumerate(filenames):
frame = 2*(i**0.5)
if round(frame) > round(last):
last = frame
else:
continue
image = imageio.imread(filename)
writer.append_data(image)
image = imageio.imread(filename)
writer.append_data(image)
import IPython
if IPython.version_info > (6,2,0,''):
display.Image(filename=anim_file)
imageio library๋ก ํ๋ จ๊ณผ์ ์์ ์์ฑํ ์ด๋ฏธ์ง๋ฅผ ์ฐ์์ผ๋ก ์ด์ด๋ถ์ฌ gif ํ์ผ์ ์์ฑํ ์ ์๋ค.
https://www.tensorflow.org/tutorials/generative/dcgan?hl=ko
https://velog.io/@wo7864/GAN-%EC%BD%94%EB%93%9C%EB%A5%BC-%ED%86%B5%ED%95%9C-%EC%9D%B4%ED%95%B41