728x90
반응형
In [45]:
# 필요한 모듈 먼저 불러오기
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
tf.reset_default_graph()
In [46]:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./mnist/data",one_hot=True)
In [47]:
total_epochs = 100
batch_size = 100
n_hidden = 256
n_input = 28 * 28
n_noise = 128
n_class = 10
In [48]:
X = tf.placeholder(tf.float32,[None,n_input])
Y = tf.placeholder(tf.float32,[None,n_class])
# 노이즈
Z = tf.placeholder(tf.float32,[None,n_noise])
In [49]:
def generator(noise,labels):
with tf.variable_scope('generator'):
# noise + labels 펼치기
inputs = tf.concat([noise,labels],1)
hidden = tf.layers.dense(inputs,n_hidden,activation=tf.nn.relu)
output = tf.layers.dense(hidden,n_input,activation=tf.nn.sigmoid)
return output
In [50]:
def discriminator(inputs, labels,reuse=None):
with tf.variable_scope('discriminator') as scope:
# 가짜 이미지, 실제 이미지 분석을 위해 모델 변수 재사용한다.
if reuse:
scope.reuse_variables()
inputs = tf.concat([inputs,labels],1)
hidden = tf.layers.dense(inputs,n_hidden,activation=tf.nn.relu)
output = tf.layers.dense(hidden,1,activation=None)
return output
In [51]:
# noise
def get_noise(batch_size,n_noise):
return np.random.uniform(-1.,1.,size=[batch_size,n_noise])
In [52]:
# 생성 모델과 판별 모델에 labels 정보를 추가하여 정보에 해당하는 이미지 생성하도록 유도
G = generator(Z,Y)
D_real = discriminator(X,Y)
D_fake = discriminator(G,Y,True)
In [53]:
# 진짜 이미지를 판별하는 D_real은 1에 가깝게
# 가짜 이미지를 판별하는 D_fake는 0에 가깝게 하는 loss
loss_D_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D_real,
labels=tf.ones_like(D_real)))
loss_D_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D_fake,
labels=tf.ones_like(D_fake)))
In [54]:
# 위 두 Loss를 더하고 최소화하도록 최적화
loss_D = loss_D_fake + loss_D_real
In [56]:
# 가짜 이미지를 진짜처럼 만들기 위해 D_fake를 최대한 1에 가깝게하는 loss
loss_G = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D_fake,
labels=tf.ones_like(D_fake)))
In [57]:
# discriminator. generator scope에서 사용된 변수 가져오기
vars_D = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,scope='discriminator')
vars_G = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,scope='generator')
train_D = tf.train.AdamOptimizer().minimize(loss_D,var_list=vars_D)
train_G = tf.train.AdamOptimizer().minimize(loss_G,var_list=vars_G)
In [60]:
total_batch = int(mnist.train.num_examples / batch_size)
loss_val_D, loss_val_G = 0,0
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(total_epochs):
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
noise = get_noise(batch_size,n_noise)
_, loss_val_D = sess.run([train_D,loss_D],feed_dict={X:batch_x,Y:batch_y,Z:noise})
_, loss_val_G = sess.run([train_G,loss_G], feed_dict={Y:batch_y,Z:noise})
print('Epoch:','%04d' % epoch,
'D loss : {:.4}'.format(loss_val_D),
'G loss : {:.4}'.format(loss_val_G))
if epoch == 0 or (epoch + 1) % 10 == 0:
sample_size = 10
noise = get_noise(sample_size,n_noise)
samples = sess.run(G,feed_dict={Y:mnist.test.labels[:sample_size], Z:noise})
fig, ax = plt.subplots(2,sample_size,figsize=(sample_size,2))
for i in range(sample_size):
ax[0][i].set_axis_off()
ax[1][i].set_axis_off()
ax[0][i].imshow(np.reshape(mnist.test.images[i], (28,28)))
ax[1][i].imshow(np.reshape(mnist.test.images[i], (28,28)))
plt.show()
print('최적화 완료!')
# 2번째 줄에 있는 이미지가 generator을 통해 생성된 MNIST data
728x90
반응형