Hi 游客

更多精彩,请登录!

比特池塘 区块链技术 正文

教你如何使用GAN为口袋妖怪上色

阿丽66
106 0 0

6 q2 r. D* h: f; x" C7 J2 w4 \在之前的Demo中,我们使用了条件GAN来生成了手写数字图像。那么除了生成数字图像以外我们还能用神经网络来干些什么呢?
& }/ j6 }, c# G3 O9 n, p3 t+ O! z5 h2 a在本案例中,我们用神经网络来给口袋妖怪的线框图上色。+ h$ l4 D8 I; w
第一步: 导入使用库
7 N5 L$ K* q( Sfrom __future__ import absolute_import, division, print_function, unicode_literals* c/ l) Y' ?5 K" _
import tensorflow as tf
  w3 }: Z" B6 m. a; t4 ktf.enable_eager_execution()3 @! g& z  n  \1 e
import numpy as np
2 Z8 O5 w) I& x8 P, X8 f- T. Mimport pandas as pd
$ Y( w  j3 f) U- x$ H# qimport os: _* I( U( E1 C) D! d: l% \
import time
% Q1 n) I4 X7 aimport 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
0 h) C. }! m3 A2 i2 D7 d* X/ \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
7 ]2 `: q9 q" x* Y$ ^IMG_WIDTH = 256
, ^1 l+ _5 X6 `1 O  z3 hIMG_HEIGHT = 256$ v: I1 n/ D; ]+ n# X6 W3 I3 b
PATH = 'dataset/'
, Y+ K4 ^3 i6 N) p* hOUTPUT_CHANNELS = 3- m  \0 D: u' Z" H+ C. i1 I/ }
LAMBDA = 100
" t. R$ \; o$ p9 `! r/ }$ iEPOCHS = 10, y# N% m; m  A3 c. o
第二步: 定义需要使用的函数+ ?, K8 K( Q$ u5 `: h6 Z) ?
图片数据加载函数,主要的作用是使用Tensorflow的io接口读入图片,并且放入tensor的对象中,方便后续使用
; z0 `/ @5 A# r9 \6 T( Ydef 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
- S! u! u% N' D% b    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)
# w# t. @5 H9 F& t- c    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对象的函数
5 z6 a& G0 P; S3 b% Y在训练过程中,我会可视化一些训练的结果以及中间状态的图片。Tensorflow的tensor对象无法直接在matplot中直接使用,因此我们需要一个函数,将tensor转成numpy对象。
7 _9 _0 b& O: Z$ \def tensor_to_array(tensor1):
/ h2 R! E, V. [% O" i; Q    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
我们每张数据图片分成了两个部分,左边部分是线框图,我们用来作为输入数据,右边部分是上色图,我们用来作为训练的目标图片。
8 v5 J( R5 h& b" E7 {0 }我们使用上面定义的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, ~

2 t0 F: k4 ~7 N: j( z# G& Y第四步: 数据增强
' }" R6 o# W  V由于我们的训练数据不够多,我们使用数据增强来增加我们的样本。从而让小样本的数据也能达到更好的效果。' Z$ u3 v# R2 j9 S" H
我们采取如下的数据增强方案:
6 ]: J% b2 e2 P/ D图片缩放, 将输入数据的图片缩放到我们指定的图片的大小随机裁剪数据归一化左右翻转$ E  r6 b! M% _# W( ~

  M* ~0 ~" e* r& f( @1 h1 j* c! }" Wdef resize(input_image, real_image, height, width):
5 B& [, }; w& L  J    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])
. _6 ~/ m. D5 I* j4 h    return cropped_image[0], cropped_image[1]& O, q6 x" T/ q8 ~2 f
def random_crop(input_image, real_image):
6 C: G# u( e3 `5 R& F    stacked_image = tf.stack([input_image, real_image], axis=0)
) C3 j7 ]: I- ]8 z' }9 f' O    cropped_image = tf.image.random_crop(stacked_image, size=[2, IMG_HEIGHT, IMG_WIDTH, 3])
; d# V8 e7 n' l    return cropped_image[0], cropped_image[1]! e# _* b* C" l' }. a
我们将上述的增强方案做成一个函数,其中左右翻转是随机进行+ {" U9 `# @2 \/ |! d
@tf.function()
1 O* |6 J/ F" S+ y. ^2 s5 [0 |def random_jitter(input_image, real_image):
6 C! E6 \! k* r# _    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)
2 j) ^0 g. W) T* ^4 b( _$ N    if tf.random.uniform(()) > 0.5:
; t2 V8 a9 U9 a! x2 u: p+ d        input_image = tf.image.flip_left_right(input_image)
( c/ J' D, q6 a, D+ r$ n' J        real_image = tf.image.flip_left_right(real_image)
; v0 L0 X6 G) ?* g$ N. f    return input_image, real_image
: u! [% T7 U4 e- [, P8 Z数据增强的效果
8 Y$ Z( `: c. u2 y' [( ^$ Y0 Wplt.figure(figsize=(6, 6))9 Z+ O1 l+ a! g) ^" B
for i in range(4):
% y8 o. S# h( |$ V    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
第五步: 训练数据的准备
1 p$ k- [$ Q0 S+ h定义训练数据跟测试数据的加载函数
8 e; g. c( |4 t6 G' z1 |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)
% M: A- Y4 P4 ^* y( {    input_image, real_image = normalize(input_image, real_image)! I/ D) f' j% O& W
    return input_image, real_image
1 a8 U; p( K  |4 @def load_image_test(image_file):
( h! F- Z1 u( M/ c0 D+ v. a5 E    input_image, real_image = load(image_file)
1 d/ J; M) P9 t* Q    input_image, real_image = resize(input_image, real_image, IMG_HEIGHT, IMG_WIDTH)
( p9 x. U, E3 b6 c/ \& H" w. `    input_image, real_image = normalize(input_image, real_image)9 i: e7 r- j$ q1 d5 `3 [% s
    return input_image, real_image
$ A& q. I. C' n使用tensorflow的DataSet来加载训练和测试数据, 定义我们的训练数据跟测试数据集对象
4 v7 Q3 F2 R" h4 V1 e. itrain_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)
$ }; K# o8 L) u1 r1 ctrain_dataset = train_dataset.batch(1)
$ y" N) Q& _% k# Y5 m/ C' Itest_dataset = tf.data.Dataset.list_files(PATH+'test/*.jpg')
; l- t: z- h! s) T/ ttest_dataset = test_dataset.map(load_image_test)
: [# B2 M, y* ptest_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模型的复杂读更加的高。
6 U# o, Q, B: [- f4 C我们先来看下生成网络跟判别网络的整体结构- _8 K" \* h5 ], x
生成网络
. H: e+ ?7 l* F+ k. _9 ^生成网络使用了U-Net的基本框架,编码阶段的每一个Block我们使用, 卷积层->BN层->LeakyReLU的方式。解码阶段的每一个Block我们使用, 反卷积->BN层->Dropout或者ReLU。其中前三个Block我们使用Dropout, 后面的我们使用ReLU。每一个编码层的Block输出还连接了与之对应的解码层的Block. 具体可以参考U-Net的skip connection.
4 x, [: s! S9 J定义编码Block
: {! k0 G- N8 }9 a' idef downsample(filters, size, apply_batchnorm=True):
" h$ _9 a: P0 @0 A  H+ }$ d    initializer = tf.random_normal_initializer(0., 0.02)
$ q  `1 k6 Z# x. q8 ], F    result = tf.keras.Sequential()
1 f  ~2 z5 `# n5 y' I' a5 _! `6 c    result.add(tf.keras.layers.Conv2D(filters, size, strides=2, padding='same', kernel_initializer=initializer, use_bias=False))
: ]; r/ _2 A$ n) H9 T6 b    if apply_batchnorm:- P) x* M# N# V8 H
        result.add(tf.keras.layers.BatchNormalization())% ?9 ~' M# ]- r
    result.add(tf.keras.layers.LeakyReLU())
9 c$ _& Z+ k$ ~& c! u3 W    return result) n2 ^% K# O! j
down_model = downsample(3, 4)
# s! k  F& E# L9 d8 a& N定义解码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()
; w* D$ M8 z% p! Q1 o    result.add(tf.keras.layers.Conv2DTranspose(filters, size, strides=2, padding='same', kernel_initializer=initializer, use_bias=False))
+ `- |9 ?. h- U; t/ F    result.add(tf.keras.layers.BatchNormalization())
/ M4 S/ M' ~  J* M    if apply_dropout:
2 l4 S/ C: T  I8 `: W6 u3 j        result.add(tf.keras.layers.Dropout(0.5))! [- i' C$ G. A; F
    result.add(tf.keras.layers.ReLU())
& U4 d% E+ v/ N    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():
5 J5 _8 R2 l4 A9 A* N" a5 E    down_stack = [
* x: q6 ]1 P5 a, r$ u& J        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)
) i" N. t8 z/ @- ~        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)
# t+ n7 C4 ]: M: x; B9 ]        downsample(512, 4), # (bs, 1, 1, 512)
1 H2 K4 }' R7 O$ |- s+ b# F    ]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)
& X* g) U+ x% y        upsample(512, 4, apply_dropout=True), # (bs, 4, 4, 1024)
# E' H$ U7 Q1 R( J: Q4 i7 ]/ D7 }0 F        upsample(512, 4, apply_dropout=True), # (bs, 8, 8, 1024)
! z/ A* \- Z4 [  T        upsample(512, 4), # (bs, 16, 16, 1024)
3 ~% F' T& A: T# l8 W        upsample(256, 4), # (bs, 32, 32, 512)6 Z4 `" v( m5 v; l, b9 l
        upsample(128, 4), # (bs, 64, 64, 256)
4 m) ~. }# f4 p* N+ l& ]3 I        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)
) P7 r. [- ?6 P' G( Q5 j: F7 ]: h    last = tf.keras.layers.Conv2DTranspose(OUTPUT_CHANNELS, 4,8 b: @( j! i' Z& o% p6 I. k
                                         strides=2,
1 R8 F6 b9 t. M1 Q3 J                                         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
8 l: s2 N2 y& `. d( {* H7 y    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])
4 x/ Y3 X! Q- D    for up, skip in zip(up_stack, skips):
: c& ~! V; b6 d- f# v  C+ c        x = up(x)
+ `, U$ m8 n, O/ D& C' {9 B8 l        x = concat([x, skip])
, U/ m' G. D3 v    x = last(x)* Q3 G  {/ a- K$ v* M3 r
    return tf.keras.Model(inputs=inputs, outputs=x)
7 ]1 P, X  g# V+ M: \" [+ z1 ggenerator = 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

& x8 i4 t: k4 I" `. R9 jdef Discriminator():
6 r3 [( C+ R7 z( f8 k6 K' S    initializer = tf.random_normal_initializer(0., 0.02)
" V; e  T/ g, P    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)
- K) O$ y' F- j0 H$ I# w! k    x = tf.keras.layers.concatenate([inp, tar])' N6 m- Z% }& h- T7 _6 M& M* m/ g
    # (batch size, 128, 128, 64)
; S% u" Q; j' L5 b& _9 B4 V    down1 = downsample(64, 4, False)(x)
( K; V6 x! ^, |% d' E   / R5 V8 D0 Z2 ?/ c" {0 e. A, J8 W1 ~
    # (batch size, 64, 64, 128)
+ V2 A6 s8 F: ?! f  H) K+ C% r    down2 = downsample(128, 4)(down1)
5 R) S1 r( _0 A$ p# {   
  L# t; u$ n3 u    # (batch size, 32, 32, 256)
' @0 e) e/ N# p    down3 = downsample(256, 4)(down2)$ s5 y- |2 Y$ H; F1 K% G
    # (batch size, 34, 34, 256)
2 z# g3 q3 L& H9 w9 ~% T    zero_pad1 = tf.keras.layers.ZeroPadding2D()(down3)3 Z) H* |2 h/ D$ a. f. k6 t3 C2 k
   
7 h" @' g- N$ E9 I! l    # (batch size, 31, 31, 512)
1 i0 J, @" U' f( [9 \3 [    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)
1 g$ l. j8 P( Q    last = tf.keras.layers.Conv2D(1, 4, strides=1, kernel_initializer=initializer)(zero_pad2)
" c" k4 \: F4 k6 m1 \& Q3 W$ k! D    return tf.keras.Model(inputs=[inp, tar], outputs=last)9 ]9 k, Z/ ~3 Y4 `  J0 @7 j' ~
discriminator = Discriminator(); \& |5 ~& o1 }
第七步: 定义损失函数和优化器
- ], e/ T0 y3 R$ O; N" T0 m- B* U/ X**& u4 y9 M- @% l# z" P% i
**6 x- ?6 w6 x) P# Q5 G
loss_object = tf.keras.losses.BinaryCrossentropy(from_logits=True)
! o* Q% H/ v3 }0 x4 h9 D. u**
2 h/ c1 ]0 M6 D; Q3 x" E5 Q/ 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)
1 c# k0 l! F! H) {9 l2 A    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)
% p7 s8 x" B* p( `( R* z, D    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)
/ X( ~) ]# l: t+ P* G) V! A3 m5 w    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)
( v' y. |  I! w% p$ l* C5 Z$ bdiscriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)2 V- [; j( g. M; S4 b0 }1 W

1 n! I: |- D* I+ P' E2 g& Y# l; X# e第八步: 定义CheckPoint函数% ?* K) G+ s' I! O% L
由于我们的训练时间较长,因此我们会保存中间的训练状态,方便后续加载继续训练
/ o, C  g+ B7 b0 B! \$ Fcheckpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
3 ^0 C8 |' F; M# u$ l                                 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
如果我们保存了之前的训练的结果,我们加载保存的数据。然后我们应用上次保存的模型来输出下我们的测试数据。
: ^) d/ \4 D3 ]def generate_images(model, test_input, tar):7 J1 ?. O1 ]! g
    prediction = model(test_input, training=True)
3 \4 C8 c  S; |    plt.figure(figsize=(15,15)). s1 j+ p* @; K4 }$ U, C
    display_list = [test_input[0], tar[0], prediction[0]]
' g7 N; d4 d7 |) T0 a, _4 n7 i    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)
0 ]- |1 J' l6 N5 z! M; P        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')
+ c6 r5 m; O3 a    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)
" X; f6 i  M# w
6 f3 g2 z8 H6 a" i% p第九步: 训练
3 M. {3 x, f6 t9 _/ P; v9 ^6 b* ^  a  |在训练中,我们输出第一张图片来查看每个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):
. ?, u, Q# X+ V1 j4 U    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
2 _' r. F6 e% O" K, Q        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,
6 u  A. C! g7 w5 D/ q  \                                               discriminator.trainable_variables)6 l+ b- U1 v6 M6 F4 ]/ b7 x
    generator_optimizer.apply_gradients(zip(generator_gradients,
. i3 m( l6 p( q* U) h5 x                                          generator.trainable_variables))
7 ]  W7 b& G/ t- j$ [1 ^    discriminator_optimizer.apply_gradients(zip(discriminator_gradients,
. o/ Q7 x9 w1 Q& \6 B5 }. w                                              discriminator.trainable_variables))
& g) I  i8 \6 V9 u+ @# e" wdef 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()
. O6 _$ j+ C! R% ^        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)
6 s' {9 i6 ^- ~        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))
1 a( Q, y! X. H        print ('训练第{}个epoch所用的时间为{:.2f}秒\n'.format(epoch + 1, time.time()-start))- J8 J: n$ ^% k2 t
fit(train_dataset, EPOCHS, test_dataset)
6 Q: H6 T0 K* A
, G% q  ~2 f$ Z1 s. U训练第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
BitMere.com 比特池塘系信息发布平台,比特池塘仅提供信息存储空间服务。
声明:该文观点仅代表作者本人,本文不代表比特池塘立场,且不构成建议,请谨慎对待。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

成为第一个吐槽的人

阿丽66 小学生
  • 粉丝

    0

  • 关注

    0

  • 主题

    2