아래 링크를 통해 이 노트북을 주피터 노트북 뷰어(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.19.0 GPU 여부: True /device:GPU:0
tf.config.experimental.get_memory_info('GPU:0')['current']
3314432
!nvidia-smi
Wed Sep 3 03:17:27 2025 +-----------------------------------------------------------------------------------------+ | NVIDIA-SMI 550.54.15 Driver Version: 550.54.15 CUDA Version: 12.4 | |-----------------------------------------+------------------------+----------------------+ | 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-SXM4-40GB Off | 00000000:00:04.0 Off | 0 | | N/A 34C P0 51W / 400W | 423MiB / 40960MiB | 2% 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.4 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) │ 2,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ leaky_re_lu (LeakyReLU) │ (None, 100) │ 0 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ dense_1 (Dense) │ (None, 784) │ 79,184 │ └─────────────────────────────────┴────────────────────────┴───────────────┘
Total params: 81,184 (317.12 KB)
Trainable params: 81,184 (317.12 KB)
Non-trainable params: 0 (0.00 B)
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) │ 78,500 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ leaky_re_lu_1 (LeakyReLU) │ (None, 100) │ 0 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ dropout (Dropout) │ (None, 100) │ 0 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ dense_3 (Dense) │ (None, 1) │ 101 │ └─────────────────────────────────┴────────────────────────┴───────────────┘
Total params: 78,601 (307.04 KB)
Trainable params: 78,601 (307.04 KB)
Non-trainable params: 0 (0.00 B)
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 Unknown size (download: Unknown size, generated: Unknown size, total: Unknown size) to /root/tensorflow_datasets/mnist/3.0.1...
Dl Completed...: 0 url [00:00, ? url/s]
Dl Size...: 0 MiB [00:00, ? MiB/s]
Extraction completed...: 0 file [00:00, ? file/s]
Generating splits...: 0%| | 0/2 [00:00<?, ? splits/s]
Generating train examples...: 0 examples [00:00, ? examples/s]
Shuffling /root/tensorflow_datasets/mnist/incomplete.B0YTKO_3.0.1/mnist-train.tfrecord*...: 0%| | 0…
Generating test examples...: 0 examples [00:00, ? examples/s]
Shuffling /root/tensorflow_datasets/mnist/incomplete.B0YTKO_3.0.1/mnist-test.tfrecord*...: 0%| | 0/…
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.7089 판별자 손실: 진짜 0.8130 가짜 0.6815
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())
에포크 001 | 시간 1.35 min | 평균 손실 >> 생성자/판별자 3.2017/0.2815 [판별자-진짜: 0.0285 판별자-가짜: 0.2530] 에포크 002 | 시간 2.65 min | 평균 손실 >> 생성자/판별자 5.3511/0.3082 [판별자-진짜: 0.0924 판별자-가짜: 0.2158] 에포크 003 | 시간 3.95 min | 평균 손실 >> 생성자/판별자 3.4550/0.6483 [판별자-진짜: 0.2925 판별자-가짜: 0.3558] 에포크 004 | 시간 5.25 min | 평균 손실 >> 생성자/판별자 2.2002/0.7970 [판별자-진짜: 0.4196 판별자-가짜: 0.3774] 에포크 005 | 시간 6.54 min | 평균 손실 >> 생성자/판별자 2.2485/0.7534 [판별자-진짜: 0.4106 판별자-가짜: 0.3428] 에포크 006 | 시간 7.84 min | 평균 손실 >> 생성자/판별자 2.0143/0.8239 [판별자-진짜: 0.4610 판별자-가짜: 0.3629] 에포크 007 | 시간 9.14 min | 평균 손실 >> 생성자/판별자 1.5902/0.9722 [판별자-진짜: 0.5287 판별자-가짜: 0.4435] 에포크 008 | 시간 10.45 min | 평균 손실 >> 생성자/판별자 1.5996/0.9435 [판별자-진짜: 0.5197 판별자-가짜: 0.4238] 에포크 009 | 시간 11.74 min | 평균 손실 >> 생성자/판별자 1.4642/1.0075 [판별자-진짜: 0.5548 판별자-가짜: 0.4527] 에포크 010 | 시간 13.03 min | 평균 손실 >> 생성자/판별자 1.3118/1.0669 [판별자-진짜: 0.5769 판별자-가짜: 0.4899] 에포크 011 | 시간 14.33 min | 평균 손실 >> 생성자/판별자 1.2982/1.0965 [판별자-진짜: 0.5846 판별자-가짜: 0.5119] 에포크 012 | 시간 15.65 min | 평균 손실 >> 생성자/판별자 1.3332/1.1464 [판별자-진짜: 0.5890 판별자-가짜: 0.5574] 에포크 013 | 시간 16.95 min | 평균 손실 >> 생성자/판별자 1.2801/1.0899 [판별자-진짜: 0.5810 판별자-가짜: 0.5088] 에포크 014 | 시간 18.25 min | 평균 손실 >> 생성자/판별자 1.1983/1.1485 [판별자-진짜: 0.5982 판별자-가짜: 0.5503] 에포크 015 | 시간 19.55 min | 평균 손실 >> 생성자/판별자 1.2948/1.1339 [판별자-진짜: 0.5888 판별자-가짜: 0.5451] 에포크 016 | 시간 20.85 min | 평균 손실 >> 생성자/판별자 1.2189/1.1476 [판별자-진짜: 0.5999 판별자-가짜: 0.5477] 에포크 017 | 시간 22.15 min | 평균 손실 >> 생성자/판별자 1.1447/1.1521 [판별자-진짜: 0.6027 판별자-가짜: 0.5494] 에포크 018 | 시간 23.46 min | 평균 손실 >> 생성자/판별자 1.2051/1.1770 [판별자-진짜: 0.6050 판별자-가짜: 0.5720] 에포크 019 | 시간 24.77 min | 평균 손실 >> 생성자/판별자 1.1601/1.1751 [판별자-진짜: 0.6055 판별자-가짜: 0.5696] 에포크 020 | 시간 26.08 min | 평균 손실 >> 생성자/판별자 1.0895/1.2320 [판별자-진짜: 0.6267 판별자-가짜: 0.6053] 에포크 021 | 시간 27.38 min | 평균 손실 >> 생성자/판별자 1.1267/1.2290 [판별자-진짜: 0.6224 판별자-가짜: 0.6066] 에포크 022 | 시간 28.69 min | 평균 손실 >> 생성자/판별자 1.0776/1.2088 [판별자-진짜: 0.6183 판별자-가짜: 0.5905] 에포크 023 | 시간 30.00 min | 평균 손실 >> 생성자/판별자 1.1012/1.1989 [판별자-진짜: 0.6128 판별자-가짜: 0.5861] 에포크 024 | 시간 31.31 min | 평균 손실 >> 생성자/판별자 1.0922/1.2316 [판별자-진짜: 0.6218 판별자-가짜: 0.6098] 에포크 025 | 시간 32.62 min | 평균 손실 >> 생성자/판별자 1.0793/1.2265 [판별자-진짜: 0.6226 판별자-가짜: 0.6039] 에포크 026 | 시간 33.94 min | 평균 손실 >> 생성자/판별자 1.0536/1.2244 [판별자-진짜: 0.6255 판별자-가짜: 0.5989] 에포크 027 | 시간 35.25 min | 평균 손실 >> 생성자/판별자 1.0676/1.2150 [판별자-진짜: 0.6199 판별자-가짜: 0.5950] 에포크 028 | 시간 36.56 min | 평균 손실 >> 생성자/판별자 1.0542/1.2198 [판별자-진짜: 0.6190 판별자-가짜: 0.6008] 에포크 029 | 시간 37.88 min | 평균 손실 >> 생성자/판별자 1.0627/1.2345 [판별자-진짜: 0.6247 판별자-가짜: 0.6098] 에포크 030 | 시간 39.20 min | 평균 손실 >> 생성자/판별자 1.0646/1.2267 [판별자-진짜: 0.6209 판별자-가짜: 0.6058] 에포크 031 | 시간 40.51 min | 평균 손실 >> 생성자/판별자 1.0067/1.2337 [판별자-진짜: 0.6261 판별자-가짜: 0.6076] 에포크 032 | 시간 41.83 min | 평균 손실 >> 생성자/판별자 1.0119/1.2565 [판별자-진짜: 0.6346 판별자-가짜: 0.6219] 에포크 033 | 시간 43.15 min | 평균 손실 >> 생성자/판별자 0.9597/1.2875 [판별자-진짜: 0.6483 판별자-가짜: 0.6392] 에포크 034 | 시간 44.47 min | 평균 손실 >> 생성자/판별자 1.0011/1.2760 [판별자-진짜: 0.6443 판별자-가짜: 0.6318] 에포크 035 | 시간 45.78 min | 평균 손실 >> 생성자/판별자 1.0123/1.2686 [판별자-진짜: 0.6386 판별자-가짜: 0.6300] 에포크 036 | 시간 47.10 min | 평균 손실 >> 생성자/판별자 0.9549/1.2813 [판별자-진짜: 0.6462 판별자-가짜: 0.6352] 에포크 037 | 시간 48.42 min | 평균 손실 >> 생성자/판별자 0.9541/1.2818 [판별자-진짜: 0.6466 판별자-가짜: 0.6352] 에포크 038 | 시간 49.73 min | 평균 손실 >> 생성자/판별자 1.0119/1.2688 [판별자-진짜: 0.6377 판별자-가짜: 0.6311] 에포크 039 | 시간 51.05 min | 평균 손실 >> 생성자/판별자 1.0722/1.2354 [판별자-진짜: 0.6208 판별자-가짜: 0.6147] 에포크 040 | 시간 52.37 min | 평균 손실 >> 생성자/판별자 0.9743/1.2629 [판별자-진짜: 0.6378 판별자-가짜: 0.6250] 에포크 041 | 시간 53.68 min | 평균 손실 >> 생성자/판별자 0.9415/1.2833 [판별자-진짜: 0.6463 판별자-가짜: 0.6370] 에포크 042 | 시간 55.00 min | 평균 손실 >> 생성자/판별자 1.0145/1.2774 [판별자-진짜: 0.6403 판별자-가짜: 0.6371] 에포크 043 | 시간 56.32 min | 평균 손실 >> 생성자/판별자 1.0383/1.2640 [판별자-진짜: 0.6339 판별자-가짜: 0.6301] 에포크 044 | 시간 57.63 min | 평균 손실 >> 생성자/판별자 0.9655/1.2717 [판별자-진짜: 0.6401 판별자-가짜: 0.6316] 에포크 045 | 시간 58.95 min | 평균 손실 >> 생성자/판별자 0.9397/1.2785 [판별자-진짜: 0.6460 판별자-가짜: 0.6325] 에포크 046 | 시간 60.27 min | 평균 손실 >> 생성자/판별자 0.9714/1.2756 [판별자-진짜: 0.6457 판별자-가짜: 0.6299] 에포크 047 | 시간 61.59 min | 평균 손실 >> 생성자/판별자 0.9898/1.2824 [판별자-진짜: 0.6428 판별자-가짜: 0.6396] 에포크 048 | 시간 62.91 min | 평균 손실 >> 생성자/판별자 0.9542/1.3062 [판별자-진짜: 0.6560 판별자-가짜: 0.6503] 에포크 049 | 시간 64.22 min | 평균 손실 >> 생성자/판별자 0.9112/1.3036 [판별자-진짜: 0.6538 판별자-가짜: 0.6498] 에포크 050 | 시간 65.53 min | 평균 손실 >> 생성자/판별자 0.9977/1.2909 [판별자-진짜: 0.6445 판별자-가짜: 0.6464] 에포크 051 | 시간 66.86 min | 평균 손실 >> 생성자/판별자 0.9861/1.2760 [판별자-진짜: 0.6407 판별자-가짜: 0.6353] 에포크 052 | 시간 68.17 min | 평균 손실 >> 생성자/판별자 0.9238/1.2929 [판별자-진짜: 0.6503 판별자-가짜: 0.6426] 에포크 053 | 시간 69.49 min | 평균 손실 >> 생성자/판별자 0.9838/1.2866 [판별자-진짜: 0.6440 판별자-가짜: 0.6426] 에포크 054 | 시간 70.81 min | 평균 손실 >> 생성자/판별자 0.9648/1.2915 [판별자-진짜: 0.6487 판별자-가짜: 0.6427] 에포크 055 | 시간 72.12 min | 평균 손실 >> 생성자/판별자 0.9433/1.2918 [판별자-진짜: 0.6489 판별자-가짜: 0.6428] 에포크 056 | 시간 73.44 min | 평균 손실 >> 생성자/판별자 0.9101/1.3034 [판별자-진짜: 0.6548 판별자-가짜: 0.6486] 에포크 057 | 시간 74.75 min | 평균 손실 >> 생성자/판별자 0.9387/1.3029 [판별자-진짜: 0.6541 판별자-가짜: 0.6488] 에포크 058 | 시간 76.06 min | 평균 손실 >> 생성자/판별자 0.9915/1.2865 [판별자-진짜: 0.6439 판별자-가짜: 0.6426] 에포크 059 | 시간 77.36 min | 평균 손실 >> 생성자/판별자 0.9222/1.3069 [판별자-진짜: 0.6569 판별자-가짜: 0.6500] 에포크 060 | 시간 78.67 min | 평균 손실 >> 생성자/판별자 0.9321/1.2962 [판별자-진짜: 0.6522 판별자-가짜: 0.6439] 에포크 061 | 시간 79.98 min | 평균 손실 >> 생성자/판별자 0.9269/1.3031 [판별자-진짜: 0.6552 판별자-가짜: 0.6479] 에포크 062 | 시간 81.29 min | 평균 손실 >> 생성자/판별자 0.9431/1.3115 [판별자-진짜: 0.6560 판별자-가짜: 0.6555] 에포크 063 | 시간 82.60 min | 평균 손실 >> 생성자/판별자 0.9665/1.2985 [판별자-진짜: 0.6532 판별자-가짜: 0.6453] 에포크 064 | 시간 83.91 min | 평균 손실 >> 생성자/판별자 0.8634/1.3240 [판별자-진짜: 0.6674 판별자-가짜: 0.6566] 에포크 065 | 시간 85.22 min | 평균 손실 >> 생성자/판별자 1.0017/1.2882 [판별자-진짜: 0.6434 판별자-가짜: 0.6448] 에포크 066 | 시간 86.54 min | 평균 손실 >> 생성자/판별자 0.9851/1.2890 [판별자-진짜: 0.6456 판별자-가짜: 0.6434] 에포크 067 | 시간 87.85 min | 평균 손실 >> 생성자/판별자 0.8728/1.3203 [판별자-진짜: 0.6643 판별자-가짜: 0.6560] 에포크 068 | 시간 89.16 min | 평균 손실 >> 생성자/판별자 0.9104/1.3181 [판별자-진짜: 0.6601 판별자-가짜: 0.6580] 에포크 069 | 시간 90.48 min | 평균 손실 >> 생성자/판별자 0.9489/1.3065 [판별자-진짜: 0.6535 판별자-가짜: 0.6530] 에포크 070 | 시간 91.80 min | 평균 손실 >> 생성자/판별자 0.9014/1.3186 [판별자-진짜: 0.6625 판별자-가짜: 0.6561] 에포크 071 | 시간 93.12 min | 평균 손실 >> 생성자/판별자 0.9126/1.3201 [판별자-진짜: 0.6605 판별자-가짜: 0.6596] 에포크 072 | 시간 94.44 min | 평균 손실 >> 생성자/판별자 0.9422/1.3129 [판별자-진짜: 0.6593 판별자-가짜: 0.6536] 에포크 073 | 시간 95.75 min | 평균 손실 >> 생성자/판별자 0.9471/1.3104 [판별자-진짜: 0.6557 판별자-가짜: 0.6547] 에포크 074 | 시간 97.07 min | 평균 손실 >> 생성자/판별자 0.8853/1.3275 [판별자-진짜: 0.6662 판별자-가짜: 0.6613] 에포크 075 | 시간 98.39 min | 평균 손실 >> 생성자/판별자 0.8909/1.3285 [판별자-진짜: 0.6642 판별자-가짜: 0.6642] 에포크 076 | 시간 99.70 min | 평균 손실 >> 생성자/판별자 0.9238/1.3083 [판별자-진짜: 0.6572 판별자-가짜: 0.6511] 에포크 077 | 시간 101.02 min | 평균 손실 >> 생성자/판별자 0.9273/1.3240 [판별자-진짜: 0.6629 판별자-가짜: 0.6611] 에포크 078 | 시간 102.33 min | 평균 손실 >> 생성자/판별자 0.9155/1.3161 [판별자-진짜: 0.6608 판별자-가짜: 0.6553] 에포크 079 | 시간 103.65 min | 평균 손실 >> 생성자/판별자 0.9030/1.3262 [판별자-진짜: 0.6640 판별자-가짜: 0.6621] 에포크 080 | 시간 104.97 min | 평균 손실 >> 생성자/판별자 0.9200/1.3185 [판별자-진짜: 0.6622 판별자-가짜: 0.6563] 에포크 081 | 시간 106.28 min | 평균 손실 >> 생성자/판별자 0.9214/1.3142 [판별자-진짜: 0.6573 판별자-가짜: 0.6568] 에포크 082 | 시간 107.59 min | 평균 손실 >> 생성자/판별자 0.9043/1.3243 [판별자-진짜: 0.6646 판별자-가짜: 0.6597] 에포크 083 | 시간 108.89 min | 평균 손실 >> 생성자/판별자 0.9324/1.3148 [판별자-진짜: 0.6587 판별자-가짜: 0.6562] 에포크 084 | 시간 110.21 min | 평균 손실 >> 생성자/판별자 0.8986/1.3215 [판별자-진짜: 0.6648 판별자-가짜: 0.6567] 에포크 085 | 시간 111.52 min | 평균 손실 >> 생성자/판별자 0.9191/1.3183 [판별자-진짜: 0.6598 판별자-가짜: 0.6585] 에포크 086 | 시간 112.82 min | 평균 손실 >> 생성자/판별자 0.9112/1.3118 [판별자-진짜: 0.6592 판별자-가짜: 0.6525] 에포크 087 | 시간 114.13 min | 평균 손실 >> 생성자/판별자 0.9056/1.3226 [판별자-진짜: 0.6641 판별자-가짜: 0.6585] 에포크 088 | 시간 115.43 min | 평균 손실 >> 생성자/판별자 0.8990/1.3229 [판별자-진짜: 0.6636 판별자-가짜: 0.6593] 에포크 089 | 시간 116.74 min | 평균 손실 >> 생성자/판별자 0.8867/1.3272 [판별자-진짜: 0.6633 판별자-가짜: 0.6639] 에포크 090 | 시간 118.05 min | 평균 손실 >> 생성자/판별자 0.9438/1.3167 [판별자-진짜: 0.6607 판별자-가짜: 0.6560] 에포크 091 | 시간 119.36 min | 평균 손실 >> 생성자/판별자 0.9290/1.3135 [판별자-진짜: 0.6578 판별자-가짜: 0.6558] 에포크 092 | 시간 120.67 min | 평균 손실 >> 생성자/판별자 0.8893/1.3156 [판별자-진짜: 0.6596 판별자-가짜: 0.6560] 에포크 093 | 시간 121.98 min | 평균 손실 >> 생성자/판별자 0.9055/1.3210 [판별자-진짜: 0.6620 판별자-가짜: 0.6590] 에포크 094 | 시간 123.29 min | 평균 손실 >> 생성자/판별자 0.9115/1.3227 [판별자-진짜: 0.6643 판별자-가짜: 0.6584] 에포크 095 | 시간 124.60 min | 평균 손실 >> 생성자/판별자 0.9483/1.3195 [판별자-진짜: 0.6589 판별자-가짜: 0.6606] 에포크 096 | 시간 125.91 min | 평균 손실 >> 생성자/판별자 0.8652/1.3300 [판별자-진짜: 0.6698 판별자-가짜: 0.6602] 에포크 097 | 시간 127.22 min | 평균 손실 >> 생성자/판별자 0.9562/1.3147 [판별자-진짜: 0.6590 판별자-가짜: 0.6557] 에포크 098 | 시간 128.53 min | 평균 손실 >> 생성자/판별자 0.9206/1.3081 [판별자-진짜: 0.6559 판별자-가짜: 0.6521] 에포크 099 | 시간 129.84 min | 평균 손실 >> 생성자/판별자 0.8965/1.3277 [판별자-진짜: 0.6651 판별자-가짜: 0.6626] 에포크 100 | 시간 131.15 min | 평균 손실 >> 생성자/판별자 0.9189/1.3113 [판별자-진짜: 0.6589 판별자-가짜: 0.6523]
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()