教你如何使用GAN为口袋妖怪上色
阿丽66
发表于 2023-1-14 11:50:51
106
0
0
在之前的Demo中,我们使用了条件GAN来生成了手写数字图像。那么除了生成数字图像以外我们还能用神经网络来干些什么呢?
在本案例中,我们用神经网络来给口袋妖怪的线框图上色。+ h$ l4 D8 I; w
第一步: 导入使用库
from __future__ import absolute_import, division, print_function, unicode_literals* c/ l) Y' ?5 K" _
import tensorflow as tf
tf.enable_eager_execution()3 @! g& z n \1 e
import numpy as np
import pandas as pd
import os: _* I( U( E1 C) D! d: l% \
import time
import matplotlib.pyplot as plt3 [/ P& i" R: W7 Z# j* V# m' s
from IPython.display import clear_output$ ]0 }5 R3 _, C- P
口袋妖怪上色的模型训练过程中,需要比较大的显存。为了保证我们的模型能在2070上顺利的运行,我们限制了显存的使用量为90%, 来避免显存不足的引起的错误。: @* A& X' c* F- O. M
config = tf.compat.v1.ConfigProto()7 n- h& j J8 |
config.gpu_options.per_process_gpu_memory_fraction = 0.9
session = tf.compat.v1.Session(config=config)5 D. i2 y* w( G) {3 _: {
定义需要使用到的常量。; X" v- h; N1 k$ l
BUFFER_SIZE = 400# r% n8 `. q9 V. u5 E& V- `
BATCH_SIZE = 1
IMG_WIDTH = 256
IMG_HEIGHT = 256$ v: I1 n/ D; ]+ n# X6 W3 I3 b
PATH = 'dataset/'
OUTPUT_CHANNELS = 3- m \0 D: u' Z" H+ C. i1 I/ }
LAMBDA = 100
EPOCHS = 10, y# N% m; m A3 c. o
第二步: 定义需要使用的函数+ ?, K8 K( Q$ u5 `: h6 Z) ?
图片数据加载函数,主要的作用是使用Tensorflow的io接口读入图片,并且放入tensor的对象中,方便后续使用
def load(image_file):+ X1 V N8 T8 k0 i
image = tf.io.read_file(image_file)" @* |3 n- ]2 o9 @' w* f
image = tf.image.decode_jpeg(image)/ F" E7 s/ T1 Y( w& V
w = tf.shape(image)[1]: \0 i0 R' Z* c5 `7 ?7 A x% H
w = w // 2
input_image = image[:, :w, :]5 @0 }" g7 a, x+ {% m
real_image = image[:, w:, :]6 M- s W c" D6 W- x. V
input_image = tf.cast(input_image, tf.float32)
real_image = tf.cast(real_image, tf.float32), h; q: `" e0 y; E
return input_image, real_image5 h. d/ m5 Z/ H' ~# {7 i3 n
tensor对象转成numpy对象的函数
在训练过程中,我会可视化一些训练的结果以及中间状态的图片。Tensorflow的tensor对象无法直接在matplot中直接使用,因此我们需要一个函数,将tensor转成numpy对象。
def tensor_to_array(tensor1):
return tensor1.numpy()1 a4 {7 w/ w* `; m" K* L
第三步: 数据可视化2 l* F6 V4 H* t4 m! S
我们先来看下我们的训练数据长成什么样。) g) j+ L! X. Q& ?7 G. k
我们每张数据图片分成了两个部分,左边部分是线框图,我们用来作为输入数据,右边部分是上色图,我们用来作为训练的目标图片。
我们使用上面定义的load函数来加载一张图片看下/ g4 O& r7 B' Z n1 F2 d2 J
input, real = load(PATH+'train/114.jpg')+ g7 [" ~8 m/ g6 S
plt.figure()' ]" o; y. X' M0 D+ p+ M) }
plt.imshow(tensor_to_array(input)/255.0)1 i7 U7 I7 Y) z) X9 \- Q
plt.figure()) V* ?% R: A. o7 R
plt.imshow(tensor_to_array(real)/255.0), [8 e3 o, [3 w: g) t, |( V* D, ~
第四步: 数据增强
由于我们的训练数据不够多,我们使用数据增强来增加我们的样本。从而让小样本的数据也能达到更好的效果。' Z$ u3 v# R2 j9 S" H
我们采取如下的数据增强方案:
图片缩放, 将输入数据的图片缩放到我们指定的图片的大小随机裁剪数据归一化左右翻转$ E r6 b! M% _# W( ~
def resize(input_image, real_image, height, width):
input_image = tf.image.resize(input_image, [height, width], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)' l3 \7 ~ Y( W" i
real_image = tf.image.resize(real_image, [height, width], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)& P. \/ T0 S* G6 t8 a4 |
return input_image, real_image+ Z/ F% {* Y/ r5 x* n; i' v0 p
def random_crop(input_image, real_image): X# ]6 K$ @7 { s
stacked_image = tf.stack([input_image, real_image], axis=0), P. l5 L' U5 S; W2 x& D
cropped_image = tf.image.random_crop(stacked_image, size=[2, IMG_HEIGHT, IMG_WIDTH, 3])
return cropped_image[0], cropped_image[1]& O, q6 x" T/ q8 ~2 f
def random_crop(input_image, real_image):
stacked_image = tf.stack([input_image, real_image], axis=0)
cropped_image = tf.image.random_crop(stacked_image, size=[2, IMG_HEIGHT, IMG_WIDTH, 3])
return cropped_image[0], cropped_image[1]! e# _* b* C" l' }. a
我们将上述的增强方案做成一个函数,其中左右翻转是随机进行+ {" U9 `# @2 \/ |! d
@tf.function()
def random_jitter(input_image, real_image):
input_image, real_image = resize(input_image, real_image, 286, 286)' R" x5 n! A! V8 F- n: V
input_image, real_image = random_crop(input_image, real_image)
if tf.random.uniform(()) > 0.5:
input_image = tf.image.flip_left_right(input_image)
real_image = tf.image.flip_left_right(real_image)
return input_image, real_image
数据增强的效果
plt.figure(figsize=(6, 6))9 Z+ O1 l+ a! g) ^" B
for i in range(4):
input_image, real_image = random_jitter(input, real)" {- s/ n( I( k/ J5 u) x7 q
plt.subplot(2, 2, i+1)# v) \# s& r: h8 R6 ~) D4 L* N. X
plt.imshow(tensor_to_array(input_image)/255.0)& q% A* Q6 |6 t) c
plt.axis('off')4 e/ P- ?6 `: W0 M3 f7 T1 h
plt.show()& }& f9 d0 q$ \( p
+ ?) X' W! s: i* P( {+ W4 L
第五步: 训练数据的准备
定义训练数据跟测试数据的加载函数
def load_image_train(image_file):9 f5 O+ ~2 U) v+ b0 M* j# a4 _( a
input_image, real_image = load(image_file); V. w# |+ E- _! Z8 r- C9 a9 G
input_image, real_image = random_jitter(input_image, real_image)
input_image, real_image = normalize(input_image, real_image)! I/ D) f' j% O& W
return input_image, real_image
def load_image_test(image_file):
input_image, real_image = load(image_file)
input_image, real_image = resize(input_image, real_image, IMG_HEIGHT, IMG_WIDTH)
input_image, real_image = normalize(input_image, real_image)9 i: e7 r- j$ q1 d5 `3 [% s
return input_image, real_image
使用tensorflow的DataSet来加载训练和测试数据, 定义我们的训练数据跟测试数据集对象
train_dataset = tf.data.Dataset.list_files(PATH+'train/*.jpg')" U& F( d& T! i; e$ H3 t! \
train_dataset = train_dataset.map(load_image_train, num_parallel_calls=tf.data.experimental.AUTOTUNE)0 Q/ O, I) e3 G8 b' O
train_dataset = train_dataset.cache().shuffle(BUFFER_SIZE)
train_dataset = train_dataset.batch(1)
test_dataset = tf.data.Dataset.list_files(PATH+'test/*.jpg')
test_dataset = test_dataset.map(load_image_test)
test_dataset = test_dataset.batch(1)# ?+ A2 }( O0 P2 b* \2 m8 M2 l5 j
第六步: 定义模型, K" j( Y% R& W1 F6 L. w7 j
口袋妖怪的上色,我们使用的是GAN模型来训练, 相比上个条件GAN生成手写数字图片,这次的GAN模型的复杂读更加的高。
我们先来看下生成网络跟判别网络的整体结构- _8 K" \* h5 ], x
生成网络
生成网络使用了U-Net的基本框架,编码阶段的每一个Block我们使用, 卷积层->BN层->LeakyReLU的方式。解码阶段的每一个Block我们使用, 反卷积->BN层->Dropout或者ReLU。其中前三个Block我们使用Dropout, 后面的我们使用ReLU。每一个编码层的Block输出还连接了与之对应的解码层的Block. 具体可以参考U-Net的skip connection.
定义编码Block
def downsample(filters, size, apply_batchnorm=True):
initializer = tf.random_normal_initializer(0., 0.02)
result = tf.keras.Sequential()
result.add(tf.keras.layers.Conv2D(filters, size, strides=2, padding='same', kernel_initializer=initializer, use_bias=False))
if apply_batchnorm:- P) x* M# N# V8 H
result.add(tf.keras.layers.BatchNormalization())% ?9 ~' M# ]- r
result.add(tf.keras.layers.LeakyReLU())
return result) n2 ^% K# O! j
down_model = downsample(3, 4)
定义解码Block" w- d T" \) b/ P, I; {) e
def upsample(filters, size, apply_dropout=False):* d0 T; z$ r( I2 y& R5 d w0 H
initializer = tf.random_normal_initializer(0., 0.02)5 k# ]) S9 V4 W5 J* w4 f
result = tf.keras.Sequential()
result.add(tf.keras.layers.Conv2DTranspose(filters, size, strides=2, padding='same', kernel_initializer=initializer, use_bias=False))
result.add(tf.keras.layers.BatchNormalization())
if apply_dropout:
result.add(tf.keras.layers.Dropout(0.5))! [- i' C$ G. A; F
result.add(tf.keras.layers.ReLU())
return result4 S- D' T' X" z3 a
up_model = upsample(3, 4)" i5 p& m- \" u' R5 p' j
定义生成网络模型- j8 \" r- D4 s7 d
def Generator():
down_stack = [
downsample(64, 4, apply_batchnorm=False), # (bs, 128, 128, 64)& ]+ _+ f G' M' [
downsample(128, 4), # (bs, 64, 64, 128)( B$ q( \9 }- u; w8 B
downsample(256, 4), # (bs, 32, 32, 256)/ m$ u- N$ @' z5 c' w, Y4 v
downsample(512, 4), # (bs, 16, 16, 512)
downsample(512, 4), # (bs, 8, 8, 512) |4 D" G9 ^6 R2 k$ {
downsample(512, 4), # (bs, 4, 4, 512)% v) S! T& Y z
downsample(512, 4), # (bs, 2, 2, 512)
downsample(512, 4), # (bs, 1, 1, 512)
]2 z7 f5 l+ W3 p, Y4 ~0 ?6 E
up_stack = [7 g$ D6 j4 `4 W
upsample(512, 4, apply_dropout=True), # (bs, 2, 2, 1024)
upsample(512, 4, apply_dropout=True), # (bs, 4, 4, 1024)
upsample(512, 4, apply_dropout=True), # (bs, 8, 8, 1024)
upsample(512, 4), # (bs, 16, 16, 1024)
upsample(256, 4), # (bs, 32, 32, 512)6 Z4 `" v( m5 v; l, b9 l
upsample(128, 4), # (bs, 64, 64, 256)
upsample(64, 4), # (bs, 128, 128, 128); D2 P9 x5 G0 n9 l' X
]$ k% S7 g2 r- x# |* Y9 Z7 t# [
initializer = tf.random_normal_initializer(0., 0.02)
last = tf.keras.layers.Conv2DTranspose(OUTPUT_CHANNELS, 4,8 b: @( j! i' Z& o% p6 I. k
strides=2,
padding='same',; x; Q( @) ]) B" M* U" j G- C# a$ v
kernel_initializer=initializer,% j3 h" c: L/ J1 J# T
activation='tanh') # (bs, 256, 256, 3)7 l$ A7 E( n% S' X9 Z! D# @2 Y& ?
concat = tf.keras.layers.Concatenate()& I. W" P. N3 }% D8 O! ~& [. Y1 \
inputs = tf.keras.layers.Input(shape=[None,None,3])0 z" i1 s1 N! C2 f$ F1 K. d
x = inputs
skips = []4 K4 Z# Q: ^* v; i ?' G9 n
for down in down_stack:4 a: y. z- [, Q4 r5 {1 J
x = down(x)) K# d- B T, I" N# |6 s
skips.append(x): }4 b. P" Y. W
skips = reversed(skips[:-1])
for up, skip in zip(up_stack, skips):
x = up(x)
x = concat([x, skip])
x = last(x)* Q3 G {/ a- K$ v* M3 r
return tf.keras.Model(inputs=inputs, outputs=x)
generator = Generator()3 S+ g8 ]/ }1 X; J# I9 V/ _" G
判别网络* u3 u; q7 q6 z7 l7 z
判别网络我们使用PatchGAN, PatchGAN又称之为马尔可夫判别器。传统的基于CNN的分类模型有很多都是在最后引入了一个全连接层,然后将判别的结果输出。然而PatchGAN却不一样,它完全由卷积层构成,最后输出的是一个纬度为N的方阵。然后计算矩阵的均值作真或者假的输出。从直观上看,输出方阵的每一个输出,是模型对原图中的一个感受野,这个感受野对应了原图中的一块地方,也称之为Patch,因此,把这种结构的GAN称之为PatchGAN。5 w6 `* L# p4 ~: N: e% s
PatchGAN中的每一个Block是由卷积层->BN层->Leaky ReLU组成的。1 K1 L+ f2 W" ]6 B9 C u. F
在我们的这个模型中,最后一层我们的输出的纬度是(Batch Size, 30, 30, 1), 其中1表示图片的通道。3 E6 |1 [" ~6 _2 _( ~& U/ y6 D) y
每个30x30的输出对应着原图的70x70的区域。详细的结构可以参考这篇论文。, \( J, a- `8 j" k% f% W
def Discriminator():
initializer = tf.random_normal_initializer(0., 0.02)
inp = tf.keras.layers.Input(shape=[None, None, 3], name='input_image')6 X6 m3 t$ P5 W* l
tar = tf.keras.layers.Input(shape=[None, None, 3], name='target_image')6 B% j8 _7 W! i# ]
# (batch size, 256, 256, channels*2)
x = tf.keras.layers.concatenate([inp, tar])' N6 m- Z% }& h- T7 _6 M& M* m/ g
# (batch size, 128, 128, 64)
down1 = downsample(64, 4, False)(x)
/ R5 V8 D0 Z2 ?/ c" {0 e. A, J8 W1 ~
# (batch size, 64, 64, 128)
down2 = downsample(128, 4)(down1)
# (batch size, 32, 32, 256)
down3 = downsample(256, 4)(down2)$ s5 y- |2 Y$ H; F1 K% G
# (batch size, 34, 34, 256)
zero_pad1 = tf.keras.layers.ZeroPadding2D()(down3)3 Z) H* |2 h/ D$ a. f. k6 t3 C2 k
# (batch size, 31, 31, 512)
conv = tf.keras.layers.Conv2D(512, 4, strides=1, kernel_initializer=initializer, use_bias=False)(zero_pad1)/ ~1 A: {/ d4 @3 u9 Z
batchnorm1 = tf.keras.layers.BatchNormalization()(conv)8 K7 P+ z& W$ y& I
leaky_relu = tf.keras.layers.LeakyReLU()(batchnorm1)/ e2 L9 w5 a; [* {
# (batch size, 33, 33, 512) E @/ a8 q$ E1 c- J4 G$ K$ k
zero_pad2 = tf.keras.layers.ZeroPadding2D()(leaky_relu) H# h9 t6 W; {$ r. f* T! C' v
# (batch size, 30, 30, 1)
last = tf.keras.layers.Conv2D(1, 4, strides=1, kernel_initializer=initializer)(zero_pad2)
return tf.keras.Model(inputs=[inp, tar], outputs=last)9 ]9 k, Z/ ~3 Y4 ` J0 @7 j' ~
discriminator = Discriminator(); \& |5 ~& o1 }
第七步: 定义损失函数和优化器
**& u4 y9 M- @% l# z" P% i
**6 x- ?6 w6 x) P# Q5 G
loss_object = tf.keras.losses.BinaryCrossentropy(from_logits=True)
**
/ p/ L# J1 y; B! G- J6 L
def discriminator_loss(disc_real_output, disc_generated_output):) H; J1 @8 c$ e+ x/ Y5 N# r
real_loss = loss_object(tf.ones_like(disc_real_output), disc_real_output)
generated_loss = loss_object(tf.zeros_like(disc_generated_output), disc_generated_output), _7 N7 k2 X( r2 d6 o! W+ w* W7 ?' y
total_disc_loss = real_loss + generated_loss! d" c6 E" I, |& _
return total_disc_loss" }3 g6 p' \; _" ]) R+ O
def generator_loss(disc_generated_output, gen_output, target):* B( D0 \5 Y( d1 X4 ~5 g4 K
gan_loss = loss_object(tf.ones_like(disc_generated_output), disc_generated_output)
l1_loss = tf.reduce_mean(tf.abs(target - gen_output))( t* Y0 A0 S3 D/ P8 N1 v
total_gen_loss = gan_loss + (LAMBDA * l1_loss)
return total_gen_loss* b3 p( H6 k# L4 R( B" {. z( ]4 I
generator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)
discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)2 V- [; j( g. M; S4 b0 }1 W
第八步: 定义CheckPoint函数% ?* K) G+ s' I! O% L
由于我们的训练时间较长,因此我们会保存中间的训练状态,方便后续加载继续训练
checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
discriminator_optimizer=discriminator_optimizer,8 K7 Z% n; @9 E5 n6 A
generator=generator,4 h/ [/ X i5 v
discriminator=discriminator)2 H$ z' ^# k$ f5 c. h& d1 m5 g0 X& K+ E( E
如果我们保存了之前的训练的结果,我们加载保存的数据。然后我们应用上次保存的模型来输出下我们的测试数据。
def generate_images(model, test_input, tar):7 J1 ?. O1 ]! g
prediction = model(test_input, training=True)
plt.figure(figsize=(15,15)). s1 j+ p* @; K4 }$ U, C
display_list = [test_input[0], tar[0], prediction[0]]
title = ['Input', 'Target', 'Predicted']/ c6 r- N) C: b% j/ c
for i in range(3):4 L% e- y1 Z; @, _( o( s
plt.subplot(1, 3, i+1)
plt.title(title). j5 I1 ?1 t; q4 w7 Z5 r
plt.imshow(tensor_to_array(display_list) * 0.5 + 0.5)1 a# o ~( Y `) I9 \
plt.axis('off')
plt.show()! d* `' B, ^5 S% n4 S; o, }0 c
ckpt_manager = tf.train.CheckpointManager(checkpoint, "./", max_to_keep=2)" S p1 G0 @2 [% M# J
if ckpt_manager.latest_checkpoint:( s G5 t/ {" x& l- C
checkpoint.restore(ckpt_manager.latest_checkpoint)' l8 i5 X4 Q% V% M6 g
for inp, tar in test_dataset.take(20):2 P5 r3 A+ u: \4 a
generate_images(generator, inp, tar)
第九步: 训练
在训练中,我们输出第一张图片来查看每个epoch给我们的预测结果带来的变化。让大家感受到其中的乐趣- }( b0 m! ?+ D% `4 E% A0 q0 t
每20个epoch我们保存一次状态7 M: g7 b: J" E v4 S! j
@tf.function! O# M) D. @( h4 C7 f
def train_step(input_image, target):
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
gen_output = generator(input_image, training=True)' f2 F8 J9 S0 y7 g. ^
disc_real_output = discriminator([input_image, target], training=True)2 U8 ?0 \& z3 E) |( z4 f( X
disc_generated_output = discriminator([input_image, gen_output], training=True)& s, n, P. ?5 O
gen_loss = generator_loss(disc_generated_output, gen_output, target)" D3 y; \6 U2 m: @. K) l/ k& K
disc_loss = discriminator_loss(disc_real_output, disc_generated_output)7 q! u2 ?3 b1 W2 E8 t& J* D/ s
generator_gradients = gen_tape.gradient(gen_loss,( Y7 K2 F. z/ N$ x" T* ~ t% A
generator.trainable_variables)3 l0 J1 u# p8 u% k- p, O7 W
discriminator_gradients = disc_tape.gradient(disc_loss,
discriminator.trainable_variables)6 l+ b- U1 v6 M6 F4 ]/ b7 x
generator_optimizer.apply_gradients(zip(generator_gradients,
generator.trainable_variables))
discriminator_optimizer.apply_gradients(zip(discriminator_gradients,
discriminator.trainable_variables))
def fit(train_ds, epochs, test_ds):* Q; m$ F& P3 V
for epoch in range(epochs):9 i' l* ~2 d- E" N9 \* l
start = time.time()
for input_image, target in train_ds:' x3 |( H& T- k. U! B
train_step(input_image, target)$ c2 ~& m7 X8 {8 p
clear_output(wait=True)" O! \6 h4 K* _0 W
( Q# o6 W3 P' S5 t% B
for example_input, example_target in test_ds.take(1):* r- t; e/ p- }( N3 W
generate_images(generator, example_input, example_target)
if (epoch + 1) % 20 == 0:" ?+ h2 f Z+ x; h# x" i
ckpt_save_path = ckpt_manager.save()* ~1 y5 D; \+ F. v! I! ^$ V
print ('保存第{}个epoch到{}\n'.format(epoch+1, ckpt_save_path))
print ('训练第{}个epoch所用的时间为{:.2f}秒\n'.format(epoch + 1, time.time()-start))- J8 J: n$ ^% k2 t
fit(train_dataset, EPOCHS, test_dataset)
训练第8个epoch所用的时间为51.33秒。: y1 H$ J* r7 J6 l' [/ n3 |& k1 D
第十步: 使用测试数据上色,查看下我们的效果 `- T) H! E8 B8 S4 F0 x/ W
for input, target in test_dataset.take(20):, @9 r' P$ k5 {# L8 ?9 N
generate_images(generator, input, target)9 _( d9 ^% P. |6 ^. z, }% x
矩池云现在已经上架 “口袋妖怪上色” 镜像;感兴趣的小伙伴可以通过矩池云官网“Jupyter 教程 Demo” 镜像中尝试使用。0 y" p" d* }" F
成为第一个吐槽的人