아래 링크를 통해 이 노트북을 주피터 노트북 뷰어(nbviewer.jupyter.org)로 보거나 구글 코랩(colab.research.google.com)에서 실행할 수 있습니다.
![]() |
![]() |
from IPython.display import Image
Image(url='https://git.io/JLAQ2', width=500)
Image(url='https://git.io/JLAQH', width=700)
Image(url='https://git.io/JLAQ7', width=700)
Image(url='https://git.io/JLAQF', width=800)
Image(url='https://git.io/JLAQb', width=700)
Image(url='https://git.io/JLAQN', width=600)
Image(url='https://git.io/JLAQA', width=600)
import tensorflow as tf
print(tf.__version__)
print("GPU 여부:", len(tf.config.list_physical_devices('GPU')) > 0)
if tf.config.list_physical_devices('GPU'):
device_name = tf.test.gpu_device_name()
else:
device_name = 'cpu:0'
print(device_name)
2.14.0 GPU 여부: True /device:GPU:0
tf.config.experimental.get_memory_usage('GPU:0')
WARNING:tensorflow:From <ipython-input-10-b9c5066405f4>:1: get_memory_usage (from tensorflow.python.framework.config) is deprecated and will be removed in a future version. Instructions for updating: Use tf.config.experimental.get_memory_info(device)['current'] instead.
0
!nvidia-smi
Sat Nov 11 01:34:19 2023 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 525.105.17 Driver Version: 525.105.17 CUDA Version: 12.0 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |===============================+======================+======================| | 0 NVIDIA A100-SXM... Off | 00000000:00:04.0 Off | 0 | | N/A 32C P0 49W / 400W | 627MiB / 40960MiB | 1% Default | | | | Disabled | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: | | GPU GI CI PID Type Process name GPU Memory | | ID ID Usage | |=============================================================================| +-----------------------------------------------------------------------------+
!lsb_release -a
No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 22.04.2 LTS Release: 22.04 Codename: jammy
#from google.colab import drive
#drive.mount('/content/drive/')
Image(url='https://git.io/JLAQp', width=600)
Image(url='https://git.io/JLAQh', width=600)
import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np
import matplotlib.pyplot as plt
## 생성자 함수를 정의합니다:
def make_generator_network(
num_hidden_layers=1,
num_hidden_units=100,
num_output_units=784):
model = tf.keras.Sequential()
for i in range(num_hidden_layers):
model.add(
tf.keras.layers.Dense(
units=num_hidden_units,
use_bias=False)
)
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Dense(
units=num_output_units, activation='tanh'))
return model
## 판별자 함수를 정의합니다:
def make_discriminator_network(
num_hidden_layers=1,
num_hidden_units=100,
num_output_units=1):
model = tf.keras.Sequential()
for i in range(num_hidden_layers):
model.add(tf.keras.layers.Dense(units=num_hidden_units))
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Dropout(rate=0.5))
model.add(
tf.keras.layers.Dense(
units=num_output_units,
activation=None)
)
return model
image_size = (28, 28)
z_size = 20
mode_z = 'uniform' # 'uniform' vs. 'normal'
gen_hidden_layers = 1
gen_hidden_size = 100
disc_hidden_layers = 1
disc_hidden_size = 100
tf.random.set_seed(1)
gen_model = make_generator_network(
num_hidden_layers=gen_hidden_layers,
num_hidden_units=gen_hidden_size,
num_output_units=np.prod(image_size))
gen_model.build(input_shape=(None, z_size))
gen_model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense (Dense) (None, 100) 2000 leaky_re_lu (LeakyReLU) (None, 100) 0 dense_1 (Dense) (None, 784) 79184 ================================================================= Total params: 81184 (317.12 KB) Trainable params: 81184 (317.12 KB) Non-trainable params: 0 (0.00 Byte) _________________________________________________________________
disc_model = make_discriminator_network(
num_hidden_layers=disc_hidden_layers,
num_hidden_units=disc_hidden_size)
disc_model.build(input_shape=(None, np.prod(image_size)))
disc_model.summary()
Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_2 (Dense) (None, 100) 78500 leaky_re_lu_1 (LeakyReLU) (None, 100) 0 dropout (Dropout) (None, 100) 0 dense_3 (Dense) (None, 1) 101 ================================================================= Total params: 78601 (307.04 KB) Trainable params: 78601 (307.04 KB) Non-trainable params: 0 (0.00 Byte) _________________________________________________________________
mnist_bldr = tfds.builder('mnist')
mnist_bldr.download_and_prepare()
mnist = mnist_bldr.as_dataset(shuffle_files=False)
def preprocess(ex, mode='uniform'):
image = ex['image']
image = tf.image.convert_image_dtype(image, tf.float32)
image = tf.reshape(image, [-1])
image = image*2 - 1.0
if mode == 'uniform':
input_z = tf.random.uniform(
shape=(z_size,), minval=-1.0, maxval=1.0)
elif mode == 'normal':
input_z = tf.random.normal(shape=(z_size,))
return input_z, image
mnist_trainset = mnist['train']
print('전처리 전: ')
example = next(iter(mnist_trainset))['image']
print('dtype: ', example.dtype, ' 최소: {} 최대: {}'.format(np.min(example), np.max(example)))
mnist_trainset = mnist_trainset.map(preprocess)
print('전처리 후: ')
example = next(iter(mnist_trainset))[0]
print('dtype: ', example.dtype, ' 최소: {} 최대: {}'.format(np.min(example), np.max(example)))
Downloading and preparing dataset 11.06 MiB (download: 11.06 MiB, generated: 21.00 MiB, total: 32.06 MiB) to /root/tensorflow_datasets/mnist/3.0.1...
Dl Completed...: 0%| | 0/5 [00:00<?, ? file/s]
Dataset mnist downloaded and prepared to /root/tensorflow_datasets/mnist/3.0.1. Subsequent calls will reuse this data. 전처리 전: dtype: <dtype: 'uint8'> 최소: 0 최대: 255 전처리 후: dtype: <dtype: 'float32'> 최소: -0.8737728595733643 최대: 0.9460210800170898
mnist_trainset = mnist_trainset.batch(32, drop_remainder=True)
input_z, input_real = next(iter(mnist_trainset))
print('input-z -- 크기:', input_z.shape)
print('input-real -- 크기:', input_real.shape)
g_output = gen_model(input_z)
print('생성자 출력 -- 크기:', g_output.shape)
d_logits_real = disc_model(input_real)
d_logits_fake = disc_model(g_output)
print('판별자 (진짜) -- 크기:', d_logits_real.shape)
print('판별자 (가짜) -- 크기:', d_logits_fake.shape)
input-z -- 크기: (32, 20) input-real -- 크기: (32, 784) 생성자 출력 -- 크기: (32, 784) 판별자 (진짜) -- 크기: (32, 1) 판별자 (가짜) -- 크기: (32, 1)
loss_fn = tf.keras.losses.BinaryCrossentropy(from_logits=True)
## 생성자 손실
g_labels_real = tf.ones_like(d_logits_fake)
g_loss = loss_fn(y_true=g_labels_real, y_pred=d_logits_fake)
print('생성자 손실: {:.4f}'.format(g_loss))
## 판별자 손실
d_labels_real = tf.ones_like(d_logits_real)
d_labels_fake = tf.zeros_like(d_logits_fake)
d_loss_real = loss_fn(y_true=d_labels_real, y_pred=d_logits_real)
d_loss_fake = loss_fn(y_true=d_labels_fake, y_pred=d_logits_fake)
print('판별자 손실: 진짜 {:.4f} 가짜 {:.4f}'
.format(d_loss_real.numpy(), d_loss_fake.numpy()))
생성자 손실: 0.6984 판별자 손실: 진짜 0.2477 가짜 0.6916
import time
num_epochs = 100
batch_size = 64
image_size = (28, 28)
z_size = 20
mode_z = 'uniform'
gen_hidden_layers = 1
gen_hidden_size = 100
disc_hidden_layers = 1
disc_hidden_size = 100
tf.random.set_seed(1)
np.random.seed(1)
if mode_z == 'uniform':
fixed_z = tf.random.uniform(
shape=(batch_size, z_size),
minval=-1, maxval=1)
elif mode_z == 'normal':
fixed_z = tf.random.normal(
shape=(batch_size, z_size))
def create_samples(g_model, input_z):
g_output = g_model(input_z, training=False)
images = tf.reshape(g_output, (batch_size, *image_size))
return (images+1)/2.0
## 데이터셋 준비
mnist_trainset = mnist['train']
mnist_trainset = mnist_trainset.map(
lambda ex: preprocess(ex, mode=mode_z))
mnist_trainset = mnist_trainset.shuffle(10000)
mnist_trainset = mnist_trainset.batch(
batch_size, drop_remainder=True)
## 모델 준비
with tf.device(device_name):
gen_model = make_generator_network(
num_hidden_layers=gen_hidden_layers,
num_hidden_units=gen_hidden_size,
num_output_units=np.prod(image_size))
gen_model.build(input_shape=(None, z_size))
disc_model = make_discriminator_network(
num_hidden_layers=disc_hidden_layers,
num_hidden_units=disc_hidden_size)
disc_model.build(input_shape=(None, np.prod(image_size)))
## 손실 함수와 옵티마이저:
loss_fn = tf.keras.losses.BinaryCrossentropy(from_logits=True)
g_optimizer = tf.keras.optimizers.Adam()
d_optimizer = tf.keras.optimizers.Adam()
all_losses = []
all_d_vals = []
epoch_samples = []
start_time = time.time()
for epoch in range(1, num_epochs+1):
epoch_losses, epoch_d_vals = [], []
for i,(input_z,input_real) in enumerate(mnist_trainset):
## 생성자 손실을 계산합니다
with tf.GradientTape() as g_tape:
g_output = gen_model(input_z)
d_logits_fake = disc_model(g_output, training=True)
labels_real = tf.ones_like(d_logits_fake)
g_loss = loss_fn(y_true=labels_real, y_pred=d_logits_fake)
# g_loss의 그래디언트를 계산합니다
g_grads = g_tape.gradient(g_loss, gen_model.trainable_variables)
# 최적화: 그래디언트를 적용합니다
g_optimizer.apply_gradients(
grads_and_vars=zip(g_grads, gen_model.trainable_variables))
## 판별자 손실을 계산합니다
with tf.GradientTape() as d_tape:
d_logits_real = disc_model(input_real, training=True)
d_labels_real = tf.ones_like(d_logits_real)
d_loss_real = loss_fn(
y_true=d_labels_real, y_pred=d_logits_real)
d_logits_fake = disc_model(g_output, training=True)
d_labels_fake = tf.zeros_like(d_logits_fake)
d_loss_fake = loss_fn(
y_true=d_labels_fake, y_pred=d_logits_fake)
d_loss = d_loss_real + d_loss_fake
## d_loss의 그래디언트를 계산합니다
d_grads = d_tape.gradient(d_loss, disc_model.trainable_variables)
## 최적화: 그래디언트를 적용합니다
d_optimizer.apply_gradients(
grads_and_vars=zip(d_grads, disc_model.trainable_variables))
epoch_losses.append(
(g_loss.numpy(), d_loss.numpy(),
d_loss_real.numpy(), d_loss_fake.numpy()))
d_probs_real = tf.reduce_mean(tf.sigmoid(d_logits_real))
d_probs_fake = tf.reduce_mean(tf.sigmoid(d_logits_fake))
epoch_d_vals.append((d_probs_real.numpy(), d_probs_fake.numpy()))
all_losses.append(epoch_losses)
all_d_vals.append(epoch_d_vals)
print(
'에포크 {:03d} | 시간 {:.2f} min | 평균 손실 >>'
' 생성자/판별자 {:.4f}/{:.4f} [판별자-진짜: {:.4f} 판별자-가짜: {:.4f}]'
.format(
epoch, (time.time() - start_time)/60,
*list(np.mean(all_losses[-1], axis=0))))
epoch_samples.append(
create_samples(gen_model, fixed_z).numpy())
WARNING:tensorflow:5 out of the last 5 calls to <function _BaseOptimizer._update_step_xla at 0x79fddd1cbbe0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details. WARNING:tensorflow:6 out of the last 6 calls to <function _BaseOptimizer._update_step_xla at 0x79fddd1cbbe0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.
에포크 001 | 시간 0.72 min | 평균 손실 >> 생성자/판별자 2.9682/0.2987 [판별자-진짜: 0.0330 판별자-가짜: 0.2658] 에포크 002 | 시간 1.39 min | 평균 손실 >> 생성자/판별자 4.9700/0.3043 [판별자-진짜: 0.0969 판별자-가짜: 0.2074] 에포크 003 | 시간 2.05 min | 평균 손실 >> 생성자/판별자 3.7117/0.6227 [판별자-진짜: 0.2698 판별자-가짜: 0.3529] 에포크 004 | 시간 2.72 min | 평균 손실 >> 생성자/판별자 2.1959/0.8859 [판별자-진짜: 0.4327 판별자-가짜: 0.4532] 에포크 005 | 시간 3.38 min | 평균 손실 >> 생성자/판별자 2.2290/0.7819 [판별자-진짜: 0.4272 판별자-가짜: 0.3548] 에포크 006 | 시간 4.05 min | 평균 손실 >> 생성자/판별자 1.6863/0.9263 [판별자-진짜: 0.5147 판별자-가짜: 0.4116] 에포크 007 | 시간 4.71 min | 평균 손실 >> 생성자/판별자 1.7057/0.9675 [판별자-진짜: 0.5167 판별자-가짜: 0.4508] 에포크 008 | 시간 5.37 min | 평균 손실 >> 생성자/판별자 1.4655/1.0108 [판별자-진짜: 0.5518 판별자-가짜: 0.4590] 에포크 009 | 시간 6.04 min | 평균 손실 >> 생성자/판별자 1.5040/0.9920 [판별자-진짜: 0.5426 판별자-가짜: 0.4494] 에포크 010 | 시간 6.71 min | 평균 손실 >> 생성자/판별자 1.4708/0.9936 [판별자-진짜: 0.5464 판별자-가짜: 0.4471] 에포크 011 | 시간 7.38 min | 평균 손실 >> 생성자/판별자 1.4586/1.0476 [판별자-진짜: 0.5591 판별자-가짜: 0.4885] 에포크 012 | 시간 8.05 min | 평균 손실 >> 생성자/판별자 1.2618/1.0958 [판별자-진짜: 0.5840 판별자-가짜: 0.5118] 에포크 013 | 시간 8.71 min | 평균 손실 >> 생성자/판별자 1.3207/1.1025 [판별자-진짜: 0.5822 판별자-가짜: 0.5203] 에포크 014 | 시간 9.37 min | 평균 손실 >> 생성자/판별자 1.2535/1.1556 [판별자-진짜: 0.5972 판별자-가짜: 0.5584] 에포크 015 | 시간 10.04 min | 평균 손실 >> 생성자/판별자 1.1510/1.1871 [판별자-진짜: 0.6151 판별자-가짜: 0.5721] 에포크 016 | 시간 10.71 min | 평균 손실 >> 생성자/판별자 1.0960/1.2090 [판별자-진짜: 0.6248 판별자-가짜: 0.5842] 에포크 017 | 시간 11.37 min | 평균 손실 >> 생성자/판별자 1.2611/1.1628 [판별자-진짜: 0.5985 판별자-가짜: 0.5644] 에포크 018 | 시간 12.04 min | 평균 손실 >> 생성자/판별자 1.0957/1.2118 [판별자-진짜: 0.6239 판별자-가짜: 0.5879] 에포크 019 | 시간 12.70 min | 평균 손실 >> 생성자/판별자 1.1300/1.1819 [판별자-진짜: 0.6089 판별자-가짜: 0.5730] 에포크 020 | 시간 13.37 min | 평균 손실 >> 생성자/판별자 1.1829/1.1976 [판별자-진짜: 0.6099 판별자-가짜: 0.5877] 에포크 021 | 시간 14.04 min | 평균 손실 >> 생성자/판별자 1.1001/1.2283 [판별자-진짜: 0.6267 판별자-가짜: 0.6016] 에포크 022 | 시간 14.71 min | 평균 손실 >> 생성자/판별자 1.0800/1.2179 [판별자-진짜: 0.6228 판별자-가짜: 0.5952] 에포크 023 | 시간 15.39 min | 평균 손실 >> 생성자/판별자 1.1102/1.2162 [판별자-진짜: 0.6203 판별자-가짜: 0.5960] 에포크 024 | 시간 16.05 min | 평균 손실 >> 생성자/판별자 1.0613/1.2296 [판별자-진짜: 0.6253 판별자-가짜: 0.6043] 에포크 025 | 시간 16.72 min | 평균 손실 >> 생성자/판별자 1.0747/1.2356 [판별자-진짜: 0.6281 판별자-가짜: 0.6075] 에포크 026 | 시간 17.39 min | 평균 손실 >> 생성자/판별자 1.1006/1.2295 [판별자-진짜: 0.6225 판별자-가짜: 0.6070] 에포크 027 | 시간 18.06 min | 평균 손실 >> 생성자/판별자 1.0458/1.2295 [판별자-진짜: 0.6270 판별자-가짜: 0.6025] 에포크 028 | 시간 18.73 min | 평균 손실 >> 생성자/판별자 1.0213/1.2526 [판별자-진짜: 0.6363 판별자-가짜: 0.6163] 에포크 029 | 시간 19.40 min | 평균 손실 >> 생성자/판별자 1.0016/1.2773 [판별자-진짜: 0.6415 판별자-가짜: 0.6357] 에포크 030 | 시간 20.06 min | 평균 손실 >> 생성자/판별자 0.9722/1.2945 [판별자-진짜: 0.6516 판별자-가짜: 0.6429] 에포크 031 | 시간 20.73 min | 평균 손실 >> 생성자/판별자 0.9942/1.2642 [판별자-진짜: 0.6401 판별자-가짜: 0.6242] 에포크 032 | 시간 21.39 min | 평균 손실 >> 생성자/판별자 1.0377/1.2560 [판별자-진짜: 0.6335 판별자-가짜: 0.6225] 에포크 033 | 시간 22.06 min | 평균 손실 >> 생성자/판별자 0.9786/1.2734 [판별자-진짜: 0.6439 판별자-가짜: 0.6295] 에포크 034 | 시간 22.72 min | 평균 손실 >> 생성자/판별자 0.9801/1.2733 [판별자-진짜: 0.6426 판별자-가짜: 0.6307] 에포크 035 | 시간 23.39 min | 평균 손실 >> 생성자/판별자 0.9964/1.2705 [판별자-진짜: 0.6423 판별자-가짜: 0.6282] 에포크 036 | 시간 24.05 min | 평균 손실 >> 생성자/판별자 1.0205/1.2722 [판별자-진짜: 0.6366 판별자-가짜: 0.6356] 에포크 037 | 시간 24.72 min | 평균 손실 >> 생성자/판별자 0.9517/1.2897 [판별자-진짜: 0.6497 판별자-가짜: 0.6400] 에포크 038 | 시간 25.38 min | 평균 손실 >> 생성자/판별자 0.9446/1.3009 [판별자-진짜: 0.6549 판별자-가짜: 0.6460] 에포크 039 | 시간 26.05 min | 평균 손실 >> 생성자/판별자 1.0219/1.2726 [판별자-진짜: 0.6393 판별자-가짜: 0.6334] 에포크 040 | 시간 26.71 min | 평균 손실 >> 생성자/판별자 0.9654/1.2797 [판별자-진짜: 0.6439 판별자-가짜: 0.6359] 에포크 041 | 시간 27.38 min | 평균 손실 >> 생성자/판별자 0.9571/1.2818 [판별자-진짜: 0.6456 판별자-가짜: 0.6362] 에포크 042 | 시간 28.04 min | 평균 손실 >> 생성자/판별자 0.9663/1.2874 [판별자-진짜: 0.6461 판별자-가짜: 0.6414] 에포크 043 | 시간 28.71 min | 평균 손실 >> 생성자/판별자 1.0119/1.2833 [판별자-진짜: 0.6457 판별자-가짜: 0.6376] 에포크 044 | 시간 29.38 min | 평균 손실 >> 생성자/판별자 0.9797/1.2826 [판별자-진짜: 0.6471 판별자-가짜: 0.6355] 에포크 045 | 시간 30.04 min | 평균 손실 >> 생성자/판별자 0.9551/1.2850 [판별자-진짜: 0.6474 판별자-가짜: 0.6375] 에포크 046 | 시간 30.71 min | 평균 손실 >> 생성자/판별자 0.9485/1.3029 [판별자-진짜: 0.6521 판별자-가짜: 0.6508] 에포크 047 | 시간 31.38 min | 평균 손실 >> 생성자/판별자 0.9814/1.2957 [판별자-진짜: 0.6482 판별자-가짜: 0.6475] 에포크 048 | 시간 32.04 min | 평균 손실 >> 생성자/판별자 0.9731/1.2807 [판별자-진짜: 0.6466 판별자-가짜: 0.6341] 에포크 049 | 시간 32.71 min | 평균 손실 >> 생성자/판별자 0.9403/1.2871 [판별자-진짜: 0.6473 판별자-가짜: 0.6398] 에포크 050 | 시간 33.38 min | 평균 손실 >> 생성자/판별자 0.9500/1.3004 [판별자-진짜: 0.6519 판별자-가짜: 0.6485] 에포크 051 | 시간 34.05 min | 평균 손실 >> 생성자/판별자 0.9708/1.2962 [판별자-진짜: 0.6507 판별자-가짜: 0.6455] 에포크 052 | 시간 34.71 min | 평균 손실 >> 생성자/판별자 0.9720/1.2942 [판별자-진짜: 0.6500 판별자-가짜: 0.6442] 에포크 053 | 시간 35.38 min | 평균 손실 >> 생성자/판별자 0.9284/1.2902 [판별자-진짜: 0.6495 판별자-가짜: 0.6407] 에포크 054 | 시간 36.04 min | 평균 손실 >> 생성자/판별자 0.9052/1.3117 [판별자-진짜: 0.6579 판별자-가짜: 0.6538] 에포크 055 | 시간 36.70 min | 평균 손실 >> 생성자/판별자 0.9440/1.3121 [판별자-진짜: 0.6572 판별자-가짜: 0.6549] 에포크 056 | 시간 37.37 min | 평균 손실 >> 생성자/판별자 0.9472/1.3049 [판별자-진짜: 0.6539 판별자-가짜: 0.6510] 에포크 057 | 시간 38.04 min | 평균 손실 >> 생성자/판별자 0.9292/1.3026 [판별자-진짜: 0.6556 판별자-가짜: 0.6471] 에포크 058 | 시간 38.71 min | 평균 손실 >> 생성자/판별자 0.9418/1.3132 [판별자-진짜: 0.6584 판별자-가짜: 0.6548] 에포크 059 | 시간 39.37 min | 평균 손실 >> 생성자/판별자 0.9499/1.2961 [판별자-진짜: 0.6510 판별자-가짜: 0.6451] 에포크 060 | 시간 40.04 min | 평균 손실 >> 생성자/판별자 0.9483/1.3055 [판별자-진짜: 0.6545 판별자-가짜: 0.6509] 에포크 061 | 시간 40.71 min | 평균 손실 >> 생성자/판별자 0.9042/1.3180 [판별자-진짜: 0.6598 판별자-가짜: 0.6582] 에포크 062 | 시간 41.38 min | 평균 손실 >> 생성자/판별자 0.9129/1.3102 [판별자-진짜: 0.6591 판별자-가짜: 0.6511] 에포크 063 | 시간 42.04 min | 평균 손실 >> 생성자/판별자 0.9112/1.3132 [판별자-진짜: 0.6583 판별자-가짜: 0.6549] 에포크 064 | 시간 42.71 min | 평균 손실 >> 생성자/판별자 0.9533/1.3041 [판별자-진짜: 0.6540 판별자-가짜: 0.6500] 에포크 065 | 시간 43.37 min | 평균 손실 >> 생성자/판별자 0.9316/1.2983 [판별자-진짜: 0.6519 판별자-가짜: 0.6463] 에포크 066 | 시간 44.03 min | 평균 손실 >> 생성자/판별자 0.9133/1.3127 [판별자-진짜: 0.6599 판별자-가짜: 0.6529] 에포크 067 | 시간 44.69 min | 평균 손실 >> 생성자/판별자 0.9513/1.3086 [판별자-진짜: 0.6563 판별자-가짜: 0.6523] 에포크 068 | 시간 45.36 min | 평균 손실 >> 생성자/판별자 0.9390/1.3004 [판별자-진짜: 0.6516 판별자-가짜: 0.6488] 에포크 069 | 시간 46.02 min | 평균 손실 >> 생성자/판별자 0.8923/1.3192 [판별자-진짜: 0.6617 판별자-가짜: 0.6574] 에포크 070 | 시간 46.69 min | 평균 손실 >> 생성자/판별자 0.9945/1.2940 [판별자-진짜: 0.6478 판별자-가짜: 0.6462] 에포크 071 | 시간 47.35 min | 평균 손실 >> 생성자/판별자 0.9231/1.3035 [판별자-진짜: 0.6546 판별자-가짜: 0.6489] 에포크 072 | 시간 48.02 min | 평균 손실 >> 생성자/판별자 0.8941/1.3198 [판별자-진짜: 0.6623 판별자-가짜: 0.6575] 에포크 073 | 시간 48.69 min | 평균 손실 >> 생성자/판별자 0.9696/1.2985 [판별자-진짜: 0.6513 판별자-가짜: 0.6472] 에포크 074 | 시간 49.35 min | 평균 손실 >> 생성자/판별자 0.9070/1.3158 [판별자-진짜: 0.6595 판별자-가짜: 0.6563] 에포크 075 | 시간 50.02 min | 평균 손실 >> 생성자/판별자 0.9233/1.3115 [판별자-진짜: 0.6577 판별자-가짜: 0.6538] 에포크 076 | 시간 50.69 min | 평균 손실 >> 생성자/판별자 0.9441/1.2990 [판별자-진짜: 0.6518 판별자-가짜: 0.6472] 에포크 077 | 시간 51.35 min | 평균 손실 >> 생성자/판별자 0.8913/1.3201 [판별자-진짜: 0.6647 판별자-가짜: 0.6554] 에포크 078 | 시간 52.01 min | 평균 손실 >> 생성자/판별자 0.9400/1.3134 [판별자-진짜: 0.6584 판별자-가짜: 0.6551] 에포크 079 | 시간 52.68 min | 평균 손실 >> 생성자/판별자 0.9224/1.3160 [판별자-진짜: 0.6599 판별자-가짜: 0.6561] 에포크 080 | 시간 53.34 min | 평균 손실 >> 생성자/판별자 0.9180/1.3117 [판별자-진짜: 0.6595 판별자-가짜: 0.6521] 에포크 081 | 시간 54.01 min | 평균 손실 >> 생성자/판별자 0.9286/1.3145 [판별자-진짜: 0.6591 판별자-가짜: 0.6554] 에포크 082 | 시간 54.67 min | 평균 손실 >> 생성자/판별자 0.9180/1.3100 [판별자-진짜: 0.6560 판별자-가짜: 0.6540] 에포크 083 | 시간 55.33 min | 평균 손실 >> 생성자/판별자 0.8849/1.3169 [판별자-진짜: 0.6593 판별자-가짜: 0.6576] 에포크 084 | 시간 55.99 min | 평균 손실 >> 생성자/판별자 0.9320/1.3058 [판별자-진짜: 0.6547 판별자-가짜: 0.6510] 에포크 085 | 시간 56.66 min | 평균 손실 >> 생성자/판별자 0.8832/1.3228 [판별자-진짜: 0.6631 판별자-가짜: 0.6598] 에포크 086 | 시간 57.33 min | 평균 손실 >> 생성자/판별자 0.9631/1.2975 [판별자-진짜: 0.6511 판별자-가짜: 0.6464] 에포크 087 | 시간 58.00 min | 평균 손실 >> 생성자/판별자 0.9304/1.3057 [판별자-진짜: 0.6557 판별자-가짜: 0.6500] 에포크 088 | 시간 58.66 min | 평균 손실 >> 생성자/판별자 0.8759/1.3222 [판별자-진짜: 0.6637 판별자-가짜: 0.6585] 에포크 089 | 시간 59.33 min | 평균 손실 >> 생성자/판별자 0.9384/1.3129 [판별자-진짜: 0.6559 판별자-가짜: 0.6570] 에포크 090 | 시간 59.99 min | 평균 손실 >> 생성자/판별자 0.9403/1.3117 [판별자-진짜: 0.6583 판별자-가짜: 0.6534] 에포크 091 | 시간 60.66 min | 평균 손실 >> 생성자/판별자 0.8884/1.3227 [판별자-진짜: 0.6658 판별자-가짜: 0.6569] 에포크 092 | 시간 61.32 min | 평균 손실 >> 생성자/판별자 0.9144/1.3193 [판별자-진짜: 0.6619 판별자-가짜: 0.6575] 에포크 093 | 시간 61.99 min | 평균 손실 >> 생성자/판별자 0.9396/1.3042 [판별자-진짜: 0.6523 판별자-가짜: 0.6518] 에포크 094 | 시간 62.65 min | 평균 손실 >> 생성자/판별자 0.8942/1.3268 [판별자-진짜: 0.6645 판별자-가짜: 0.6623] 에포크 095 | 시간 63.32 min | 평균 손실 >> 생성자/판별자 0.8894/1.3291 [판별자-진짜: 0.6665 판별자-가짜: 0.6626] 에포크 096 | 시간 63.99 min | 평균 손실 >> 생성자/판별자 0.9248/1.3169 [판별자-진짜: 0.6609 판별자-가짜: 0.6560] 에포크 097 | 시간 64.65 min | 평균 손실 >> 생성자/판별자 0.8919/1.3169 [판별자-진짜: 0.6624 판별자-가짜: 0.6545] 에포크 098 | 시간 65.32 min | 평균 손실 >> 생성자/판별자 0.9275/1.3183 [판별자-진짜: 0.6610 판별자-가짜: 0.6573] 에포크 099 | 시간 65.99 min | 평균 손실 >> 생성자/판별자 0.9424/1.3100 [판별자-진짜: 0.6585 판별자-가짜: 0.6515] 에포크 100 | 시간 66.65 min | 평균 손실 >> 생성자/판별자 0.8891/1.3146 [판별자-진짜: 0.6596 판별자-가짜: 0.6550]
import itertools
fig = plt.figure(figsize=(16, 6))
## 손실 그래프
ax = fig.add_subplot(1, 2, 1)
g_losses = [item[0] for item in itertools.chain(*all_losses)]
d_losses = [item[1]/2.0 for item in itertools.chain(*all_losses)]
plt.plot(g_losses, label='Generator loss', alpha=0.95)
plt.plot(d_losses, label='Discriminator loss', alpha=0.95)
plt.legend(fontsize=20)
ax.set_xlabel('Iteration', size=15)
ax.set_ylabel('Loss', size=15)
epochs = np.arange(1, 101)
epoch2iter = lambda e: e*len(all_losses[-1])
epoch_ticks = [1, 20, 40, 60, 80, 100]
newpos = [epoch2iter(e) for e in epoch_ticks]
ax2 = ax.twiny()
ax2.set_xticks(newpos)
ax2.set_xticklabels(epoch_ticks)
ax2.xaxis.set_ticks_position('bottom')
ax2.xaxis.set_label_position('bottom')
ax2.spines['bottom'].set_position(('outward', 60))
ax2.set_xlabel('Epoch', size=15)
ax2.set_xlim(ax.get_xlim())
ax.tick_params(axis='both', which='major', labelsize=15)
ax2.tick_params(axis='both', which='major', labelsize=15)
## 판별자의 출력
ax = fig.add_subplot(1, 2, 2)
d_vals_real = [item[0] for item in itertools.chain(*all_d_vals)]
d_vals_fake = [item[1] for item in itertools.chain(*all_d_vals)]
plt.plot(d_vals_real, alpha=0.75, label=r'Real: $D(\mathbf{x})$')
plt.plot(d_vals_fake, alpha=0.75, label=r'Fake: $D(G(\mathbf{z}))$')
plt.legend(fontsize=20)
ax.set_xlabel('Iteration', size=15)
ax.set_ylabel('Discriminator output', size=15)
ax2 = ax.twiny()
ax2.set_xticks(newpos)
ax2.set_xticklabels(epoch_ticks)
ax2.xaxis.set_ticks_position('bottom')
ax2.xaxis.set_label_position('bottom')
ax2.spines['bottom'].set_position(('outward', 60))
ax2.set_xlabel('Epoch', size=15)
ax2.set_xlim(ax.get_xlim())
ax.tick_params(axis='both', which='major', labelsize=15)
ax2.tick_params(axis='both', which='major', labelsize=15)
plt.show()
selected_epochs = [1, 2, 4, 10, 50, 100]
fig = plt.figure(figsize=(10, 14))
for i,e in enumerate(selected_epochs):
for j in range(5):
ax = fig.add_subplot(6, 5, i*5+j+1)
ax.set_xticks([])
ax.set_yticks([])
if j == 0:
ax.text(
-0.06, 0.5, 'Epoch {}'.format(e),
rotation=90, size=18, color='red',
horizontalalignment='right',
verticalalignment='center',
transform=ax.transAxes)
image = epoch_samples[e-1][j]
ax.imshow(image, cmap='gray_r')
plt.show()