Hi 游客

更多精彩,请登录!

比特池塘 区块链技术 正文

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

阿丽66
231 0 0

$ a5 m. f8 h) ?' o! H7 |在之前的Demo中,我们使用了条件GAN来生成了手写数字图像。那么除了生成数字图像以外我们还能用神经网络来干些什么呢?. q; I: O, H/ K; Y
在本案例中,我们用神经网络来给口袋妖怪的线框图上色。/ d: c7 V5 o/ Y( D3 j4 y2 I1 G; ^
第一步: 导入使用库
3 \! V# f; `7 P. g1 yfrom __future__ import absolute_import, division, print_function, unicode_literals2 u3 k) f3 @8 ^4 R2 V+ P! b
import tensorflow as tf
$ r+ A/ X0 G7 _/ E* @$ _- b) }- ^tf.enable_eager_execution()5 A2 m/ x# N0 B, K2 T& d0 i6 r* u
import numpy as np# P2 X/ N& H: S& d4 Q! u
import pandas as pd
0 b8 `; J  b+ P) U" himport os+ U/ I6 i2 q) R0 u; t
import time
" Y# p% k- Y; o9 ]" himport matplotlib.pyplot as plt
% _* z8 K$ m1 N: Hfrom IPython.display import clear_output9 B5 S4 N4 A' F: H
口袋妖怪上色的模型训练过程中,需要比较大的显存。为了保证我们的模型能在2070上顺利的运行,我们限制了显存的使用量为90%, 来避免显存不足的引起的错误。! f7 G% P& a; T
config = tf.compat.v1.ConfigProto()8 V5 M( ^( o% W' F2 N
config.gpu_options.per_process_gpu_memory_fraction = 0.9
$ V7 p/ D. n2 E9 usession = tf.compat.v1.Session(config=config)  D4 q- j8 @& `) m! b
定义需要使用到的常量。( D5 ^* X1 [" [( w$ f3 R' r
BUFFER_SIZE = 400
$ ]5 v- h$ |5 _$ P- Y- FBATCH_SIZE = 1
8 v; D" p( O  EIMG_WIDTH = 256
) @: G+ |& [; z2 H- wIMG_HEIGHT = 256
2 a. E8 t: V7 n: M  dPATH = 'dataset/'
" y" i. V& J+ i: j9 L" _/ J; j" cOUTPUT_CHANNELS = 30 z2 |% I* ^% w: g
LAMBDA = 100
/ B: u$ o; ~* K. {) W" J' l# vEPOCHS = 10" R4 B. V6 B5 g3 l6 o7 f
第二步: 定义需要使用的函数
4 [( J8 A' _  A3 M1 n8 c图片数据加载函数,主要的作用是使用Tensorflow的io接口读入图片,并且放入tensor的对象中,方便后续使用
+ K% h/ m8 ]! b( a% D4 s( jdef load(image_file):9 c8 U) S% H8 c6 x& X
    image = tf.io.read_file(image_file)! V$ r' C5 _: M
    image = tf.image.decode_jpeg(image)
3 F  [2 p2 U: [; \5 l    w = tf.shape(image)[1]
( x8 Q  q, |) z" B6 k# w    w = w // 25 P7 Z* p. T1 U& @+ T
    input_image = image[:, :w, :]
2 f* ~( H& v/ w+ n# ^  r    real_image = image[:, w:, :]
0 g  h8 q7 j, D2 {8 {    input_image = tf.cast(input_image, tf.float32)4 z( ^$ T% T2 b$ E( D8 x5 d
    real_image = tf.cast(real_image, tf.float32)& q9 `  w- |* A4 W2 s
    return input_image, real_image
, c+ |8 M: F6 H+ a* A" M- i$ jtensor对象转成numpy对象的函数
2 M  c* ~$ L% k0 ]- u( {在训练过程中,我会可视化一些训练的结果以及中间状态的图片。Tensorflow的tensor对象无法直接在matplot中直接使用,因此我们需要一个函数,将tensor转成numpy对象。
; Y2 ]; e" t" J7 U* u3 S9 x2 a  i% Ldef tensor_to_array(tensor1):& h" f: E2 f! @6 F$ \
    return tensor1.numpy()
3 V6 ~0 r, e2 y, x5 o# s# w$ I第三步: 数据可视化+ M1 G1 A5 W( u" P# v: m
我们先来看下我们的训练数据长成什么样。
0 w- h, z# A+ W! [( U% _2 m) b; j3 i我们每张数据图片分成了两个部分,左边部分是线框图,我们用来作为输入数据,右边部分是上色图,我们用来作为训练的目标图片。
8 F4 f6 u5 |& v" Q: W2 W3 c我们使用上面定义的load函数来加载一张图片看下
/ o- r: H8 V/ s+ n5 k8 W' F' i. A, O" r: vinput, real = load(PATH+'train/114.jpg')  m, v1 U6 _+ V, A8 d# A
plt.figure()6 `$ z) @( I$ v! X& |
plt.imshow(tensor_to_array(input)/255.0)
% C, I: H( L% U" K( C6 d9 m5 Splt.figure()4 t3 S+ J+ Q0 @, H; F& p' d
plt.imshow(tensor_to_array(real)/255.0)4 V, ]8 j9 k. l4 h0 ?& N0 S% v
3 R) c# S& n1 h; e! x
第四步: 数据增强/ e8 Q4 q3 @) X5 ~" A7 V3 F% o
由于我们的训练数据不够多,我们使用数据增强来增加我们的样本。从而让小样本的数据也能达到更好的效果。, }) {$ P8 ~! M( ?: N
我们采取如下的数据增强方案:2 S* }* ^" ?, U: g/ f1 f; k% F
图片缩放, 将输入数据的图片缩放到我们指定的图片的大小随机裁剪数据归一化左右翻转  E8 [* I% T# {2 [

- f' o2 W+ z. ]def resize(input_image, real_image, height, width):) h$ D# o- P7 V( W+ I/ h" ]6 K
    input_image = tf.image.resize(input_image, [height, width], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
2 H4 ]9 F& c3 U& l. m; V1 ?2 P    real_image = tf.image.resize(real_image, [height, width], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
  M" O5 ~" E0 `7 R% N+ \0 x4 \0 p6 s    return input_image, real_image
' d* y6 I* b4 O& `& kdef random_crop(input_image, real_image):& F9 F1 u* r' t
    stacked_image = tf.stack([input_image, real_image], axis=0)
/ f! a2 h2 X# u: Z$ u    cropped_image = tf.image.random_crop(stacked_image, size=[2, IMG_HEIGHT, IMG_WIDTH, 3])& Z2 n8 l: J  N  ]& k7 Z$ B
    return cropped_image[0], cropped_image[1]
. p( S) X$ }% ~0 K' t& u# @def random_crop(input_image, real_image):
/ B) f' F6 p: d- f% X3 N    stacked_image = tf.stack([input_image, real_image], axis=0); J7 F  d; X4 R+ n- e
    cropped_image = tf.image.random_crop(stacked_image, size=[2, IMG_HEIGHT, IMG_WIDTH, 3])  n7 f; i' C0 b0 Y& i  \* z% o
    return cropped_image[0], cropped_image[1]
" r2 E0 N% t, s* G: b  D4 `- X我们将上述的增强方案做成一个函数,其中左右翻转是随机进行
6 z8 A1 s" A( Z; R) a@tf.function()
" v  x: j4 W- r2 ]8 Udef random_jitter(input_image, real_image):0 i! `% D5 _0 G) ?+ t
    input_image, real_image = resize(input_image, real_image, 286, 286)
1 N- k: `+ f: e: r% t) e, v    input_image, real_image = random_crop(input_image, real_image)
5 s6 K+ H2 O. I5 ]7 v( r    if tf.random.uniform(()) > 0.5:' k0 n" O2 S; I  l6 m" n0 z
        input_image = tf.image.flip_left_right(input_image)
* q. W* [) ^! t7 `( n        real_image = tf.image.flip_left_right(real_image)
- Y' d3 H5 t* J) y/ p0 }' [    return input_image, real_image1 m% X% d+ V0 T+ a1 W7 J! A; c
数据增强的效果( ~$ T5 d7 I/ S3 p
plt.figure(figsize=(6, 6))
. l$ e& `  m6 w; O1 j4 t0 L) q2 a9 mfor i in range(4):1 ]6 Y- w8 N3 S) j
    input_image, real_image = random_jitter(input, real)
4 K5 n+ h4 K! X* V) `- X    plt.subplot(2, 2, i+1)
1 j- ^! m* N  ], s, e+ d$ C) j3 a% @    plt.imshow(tensor_to_array(input_image)/255.0)9 G" C2 T: M) \1 v; f4 U
    plt.axis('off')( O  M! K( m( D( s# v- \
plt.show()! x0 r, l$ G- b% L& L9 C
, i* n. F" l# m( \* F. I
第五步: 训练数据的准备: M, @% ]. a5 [% i/ c. e
定义训练数据跟测试数据的加载函数
' r& w0 @: f7 Rdef load_image_train(image_file):
4 {' E2 a% k: N/ ~    input_image, real_image = load(image_file)
; Z- D; J3 M8 d! p6 p    input_image, real_image = random_jitter(input_image, real_image)
1 Y% a' N! D' y+ R    input_image, real_image = normalize(input_image, real_image). l6 x5 K, r3 w* D' q
    return input_image, real_image
' P- K, _) R: g9 m8 wdef load_image_test(image_file):
4 g8 E1 f' Q6 e3 D' g7 V. z    input_image, real_image = load(image_file)
8 i5 X' v  R, x7 R' E5 r    input_image, real_image = resize(input_image, real_image, IMG_HEIGHT, IMG_WIDTH): w0 z; B0 S) F% D/ \3 d+ e- p
    input_image, real_image = normalize(input_image, real_image)
7 N  @  z' W) `, R9 M* X: L3 F    return input_image, real_image
" n& ?+ B9 b2 m% s  a/ l/ j4 |# @使用tensorflow的DataSet来加载训练和测试数据, 定义我们的训练数据跟测试数据集对象
' ]1 H+ ~5 b# O; a5 M. b& h) R9 P" Rtrain_dataset = tf.data.Dataset.list_files(PATH+'train/*.jpg')6 W% D# A+ i0 a5 C, w! y  h
train_dataset = train_dataset.map(load_image_train, num_parallel_calls=tf.data.experimental.AUTOTUNE)
5 @+ W3 E& @3 m* y$ ]' e& w6 f; Z! wtrain_dataset = train_dataset.cache().shuffle(BUFFER_SIZE)
2 X9 h1 F. T+ ]! v6 i3 M" x* k$ otrain_dataset = train_dataset.batch(1)
0 B. `0 m$ j$ O+ H( j" Vtest_dataset = tf.data.Dataset.list_files(PATH+'test/*.jpg')( ?8 w7 K2 `4 z* ^- [  B
test_dataset = test_dataset.map(load_image_test)
: [( D3 c8 N( k' \# W8 _test_dataset = test_dataset.batch(1)% m4 \& y; ^: b( T8 _
第六步: 定义模型
3 U3 ]5 O3 f2 q/ |6 Y, ^4 f口袋妖怪的上色,我们使用的是GAN模型来训练, 相比上个条件GAN生成手写数字图片,这次的GAN模型的复杂读更加的高。0 {, |' B9 D* q8 m# F% Z$ q% Z$ X
我们先来看下生成网络跟判别网络的整体结构* E' k+ Y: r0 G/ U9 G
生成网络
- h# C# j; y& `* d生成网络使用了U-Net的基本框架,编码阶段的每一个Block我们使用, 卷积层->BN层->LeakyReLU的方式。解码阶段的每一个Block我们使用, 反卷积->BN层->Dropout或者ReLU。其中前三个Block我们使用Dropout, 后面的我们使用ReLU。每一个编码层的Block输出还连接了与之对应的解码层的Block. 具体可以参考U-Net的skip connection.
1 H) G4 Z& W, \: i# T定义编码Block2 P3 x1 T* G8 h- o6 C: V/ `
def downsample(filters, size, apply_batchnorm=True):
* L% i5 e4 M0 S. `    initializer = tf.random_normal_initializer(0., 0.02)
/ z7 B1 A( F' I% e    result = tf.keras.Sequential(). A$ W7 z1 M6 Y2 }- s! [; y
    result.add(tf.keras.layers.Conv2D(filters, size, strides=2, padding='same', kernel_initializer=initializer, use_bias=False))6 X$ }" O( ~* c* [, H
    if apply_batchnorm:1 i- L4 y1 R( L, Z3 G
        result.add(tf.keras.layers.BatchNormalization())" n5 |5 M- Q: E
    result.add(tf.keras.layers.LeakyReLU())
/ x3 V7 f- x& R. c+ e4 C/ ^6 z    return result7 G0 D. R( `3 P% J: B. P
down_model = downsample(3, 4)
7 C, _9 {- ^0 J, p* {定义解码Block
! C" h$ u* F, b% A- ?def upsample(filters, size, apply_dropout=False):
7 e/ X, C" r; i: S# [9 Y    initializer = tf.random_normal_initializer(0., 0.02)  o7 W. v- Z3 |7 `3 Z- {  B5 Z1 d
    result = tf.keras.Sequential()
$ V5 E5 y2 j, `' V4 C    result.add(tf.keras.layers.Conv2DTranspose(filters, size, strides=2, padding='same', kernel_initializer=initializer, use_bias=False))
3 F- p3 S9 [, j    result.add(tf.keras.layers.BatchNormalization())( B# N4 r( a- X2 v( b8 |
    if apply_dropout:
: }: O) z) V, Q& z. k* X6 k        result.add(tf.keras.layers.Dropout(0.5))# H: m7 ^: J# q) v; D9 R% Y
    result.add(tf.keras.layers.ReLU())
( v/ B1 d- r9 U6 V2 z- S& W9 h    return result
( |! a2 g) B, ^' b( Q. uup_model = upsample(3, 4)
( `- |$ N7 O8 b" T2 X' x定义生成网络模型
3 F/ G: N5 P. bdef Generator():' y  d: t3 B7 l" Q
    down_stack = [$ X8 }3 V1 w, V+ K0 L! T
        downsample(64, 4, apply_batchnorm=False), # (bs, 128, 128, 64)
; v$ `- F; ~$ d) r" H( {8 ?- A6 r' @6 |        downsample(128, 4), # (bs, 64, 64, 128)
& {! ^% x/ \9 Y* X        downsample(256, 4), # (bs, 32, 32, 256)
8 B  l6 v) `; S/ y0 U0 b        downsample(512, 4), # (bs, 16, 16, 512)
4 j& s/ l# `1 ^+ A5 G$ p        downsample(512, 4), # (bs, 8, 8, 512), U% o4 G) m9 ?( N( q! q' L1 T
        downsample(512, 4), # (bs, 4, 4, 512)1 o; n$ ^2 H* w$ W  z. w
        downsample(512, 4), # (bs, 2, 2, 512)4 r0 P% v- e( p) D" H  z
        downsample(512, 4), # (bs, 1, 1, 512)2 t+ N2 X' x& R( w: `+ q
    ]6 M0 G/ k  [' Y
    up_stack = [
2 o, C$ Q" i: R0 X" k) T        upsample(512, 4, apply_dropout=True), # (bs, 2, 2, 1024)
- O+ G: q6 ?1 j) S8 J# O+ z" n        upsample(512, 4, apply_dropout=True), # (bs, 4, 4, 1024)" U6 i: |1 W% F* Q
        upsample(512, 4, apply_dropout=True), # (bs, 8, 8, 1024)
, B& K3 P$ T8 h' A) D6 y" f4 l        upsample(512, 4), # (bs, 16, 16, 1024)4 E/ x) m! f8 |$ K1 K
        upsample(256, 4), # (bs, 32, 32, 512), z: ~- R0 z( u6 G1 \# c9 o7 h
        upsample(128, 4), # (bs, 64, 64, 256)
7 x8 s8 l; |) l/ f1 {  _        upsample(64, 4), # (bs, 128, 128, 128)
' P# `& d' v+ r% z- a0 N    ]
9 ~6 J4 ?0 X, i  @    initializer = tf.random_normal_initializer(0., 0.02)
. J7 e5 E! C9 |# k! F# k  H* n    last = tf.keras.layers.Conv2DTranspose(OUTPUT_CHANNELS, 4,
' f+ t# g2 [6 I# ?! [                                         strides=2,+ i6 m7 q8 y# A* i- k" g
                                         padding='same',
0 s; ^7 i/ f9 |, r% X9 `                                         kernel_initializer=initializer,
8 q( g9 n9 D$ L* i6 G                                         activation='tanh') # (bs, 256, 256, 3)6 b) r5 B( @! q  T" o
    concat = tf.keras.layers.Concatenate()8 k" {: A- C7 |" Z# L1 |
    inputs = tf.keras.layers.Input(shape=[None,None,3])1 }9 q) w6 S/ x  G
    x = inputs
; ?% r5 ^0 j$ R. `    skips = []
( N. d# v' w/ c; p, h$ W    for down in down_stack:
, R/ O9 K5 A( z0 q  u% u0 k' J        x = down(x)
7 A- M2 g6 ~! o+ g% h! f        skips.append(x)
. C& X# @* A/ {9 X6 l; N+ w$ \; D, R    skips = reversed(skips[:-1])- f' d( o9 B% i3 F
    for up, skip in zip(up_stack, skips):. c8 e" v5 a8 \
        x = up(x)& o8 u, [& @0 c. G+ \. y
        x = concat([x, skip])
" v& W* X2 o  z3 E; V7 e" @    x = last(x)3 q# `+ w8 X% b% d% O; S7 G
    return tf.keras.Model(inputs=inputs, outputs=x)6 M/ p. }+ ~/ k
generator = Generator()
2 s. v) G- z. [) F# v. r判别网络+ X$ W" i' V# A, R8 n* [" _" |
判别网络我们使用PatchGAN, PatchGAN又称之为马尔可夫判别器。传统的基于CNN的分类模型有很多都是在最后引入了一个全连接层,然后将判别的结果输出。然而PatchGAN却不一样,它完全由卷积层构成,最后输出的是一个纬度为N的方阵。然后计算矩阵的均值作真或者假的输出。从直观上看,输出方阵的每一个输出,是模型对原图中的一个感受野,这个感受野对应了原图中的一块地方,也称之为Patch,因此,把这种结构的GAN称之为PatchGAN。
; q, V- w1 T! L9 ]2 Q6 g' M+ }PatchGAN中的每一个Block是由卷积层->BN层->Leaky ReLU组成的。/ n7 J9 d8 h# p9 u) S& b3 W0 W* S
在我们的这个模型中,最后一层我们的输出的纬度是(Batch Size, 30, 30, 1), 其中1表示图片的通道。6 Q! s" a' `9 u: }  q, K
每个30x30的输出对应着原图的70x70的区域。详细的结构可以参考这篇论文。
8 D+ f0 f0 X* e) ?; `: r) F+ @: C
) ]- W" N+ [! B# N2 Xdef Discriminator():6 \% r7 h% a! J% t1 I
    initializer = tf.random_normal_initializer(0., 0.02)- d% P8 k" M- a& A& X' Z0 s- t  K1 \
    inp = tf.keras.layers.Input(shape=[None, None, 3], name='input_image')
+ y+ Z9 n0 [' n# l* ~    tar = tf.keras.layers.Input(shape=[None, None, 3], name='target_image'): `* K* h4 _9 z" e( A& M
    # (batch size, 256, 256, channels*2)
* s& P* J8 Y( v) h    x = tf.keras.layers.concatenate([inp, tar])9 X2 e" }3 T1 g" ~* K
    # (batch size, 128, 128, 64)
9 f! U/ W- g; P$ z2 S6 x- A5 ~    down1 = downsample(64, 4, False)(x)
- |7 \0 q. b4 s( I( k   
+ n6 b" X: C6 ?9 n    # (batch size, 64, 64, 128)
; `* R2 r& w% M  D# o' e    down2 = downsample(128, 4)(down1)
5 M4 n! v2 H) J  G5 F/ M   
2 \% y* I7 q! I1 C    # (batch size, 32, 32, 256)
' Z, T4 z( i. D! ?+ x/ M    down3 = downsample(256, 4)(down2)
2 s  s3 {6 M0 g5 I0 G, n1 U3 ~    # (batch size, 34, 34, 256): P" g- R1 S! ], ~
    zero_pad1 = tf.keras.layers.ZeroPadding2D()(down3)1 G' l  I0 s: c# r+ U* `) E/ X
   , A2 U4 d: A# p0 C0 u3 C) r
    # (batch size, 31, 31, 512)+ ]# [3 j7 w% c9 j' ?
    conv = tf.keras.layers.Conv2D(512, 4, strides=1, kernel_initializer=initializer, use_bias=False)(zero_pad1)
" f( P) S2 `' U2 X* k    batchnorm1 = tf.keras.layers.BatchNormalization()(conv)
1 _$ b# |$ l  u# o# A; |& i& f# Z    leaky_relu = tf.keras.layers.LeakyReLU()(batchnorm1)4 ?2 i2 M3 t2 T- Z$ y. @$ H3 |- u2 \; ~
    # (batch size, 33, 33, 512)' k$ \3 U1 }+ ~+ D
    zero_pad2 = tf.keras.layers.ZeroPadding2D()(leaky_relu)
% Z! }( @' {0 [; r- F' b" `    # (batch size, 30, 30, 1)% b' }* ~4 h' K5 [4 D6 X6 D& i
    last = tf.keras.layers.Conv2D(1, 4, strides=1, kernel_initializer=initializer)(zero_pad2)/ I9 T" Z- S( J  K" w* C# ~" t' T' \
    return tf.keras.Model(inputs=[inp, tar], outputs=last)% b! M' U. R- [' I" u
discriminator = Discriminator()- o, i, L4 U( S. m
第七步: 定义损失函数和优化器5 c% S( O0 Q1 B& i
**  x, h  o& P/ q
**3 S$ c' r* y8 v- U
loss_object = tf.keras.losses.BinaryCrossentropy(from_logits=True)
+ V# `+ N4 G: a  F**1 I3 I$ N! M1 v% p" ]

7 \! T) Y# T) l1 G8 I  xdef discriminator_loss(disc_real_output, disc_generated_output):6 _/ S, L# b1 \  W
    real_loss = loss_object(tf.ones_like(disc_real_output), disc_real_output)
& I, [% o( Y# A+ J' `$ d/ w# g. V" I    generated_loss = loss_object(tf.zeros_like(disc_generated_output), disc_generated_output)& O3 O! w: n/ h$ x5 k
    total_disc_loss = real_loss + generated_loss
' ?) V8 |0 H  _9 u0 R' p    return total_disc_loss' F; x  Q2 l! R, e  o! o- R
def generator_loss(disc_generated_output, gen_output, target):
0 {/ ]# c+ T, H) T. e/ r) I    gan_loss = loss_object(tf.ones_like(disc_generated_output), disc_generated_output)
* o2 S6 |6 L9 r    l1_loss = tf.reduce_mean(tf.abs(target - gen_output))% l) I; y3 ^' L
    total_gen_loss = gan_loss + (LAMBDA * l1_loss)' W! V8 i/ `9 }, G# v7 K; e
    return total_gen_loss
4 L) ~2 D0 s7 T$ o- F3 wgenerator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)2 B+ h' l* ~7 {
discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)
! }; p9 n& }( u' q& h* ?3 G
; b) z+ I' ]- {4 O第八步: 定义CheckPoint函数& B' E+ X# i* ~
由于我们的训练时间较长,因此我们会保存中间的训练状态,方便后续加载继续训练
* W5 a- m4 V# |checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,5 V* ~% M& _$ x7 O! t, |( R' z
                                 discriminator_optimizer=discriminator_optimizer,
" y6 k" R( L/ \3 F+ \3 c8 x3 G$ o                                 generator=generator,' I4 n  e( ~& v3 c
                                 discriminator=discriminator)* w& N3 k3 J/ M. F% p4 ^5 J
如果我们保存了之前的训练的结果,我们加载保存的数据。然后我们应用上次保存的模型来输出下我们的测试数据。
5 m1 ^' V0 M4 e5 F1 cdef generate_images(model, test_input, tar):
% J' _5 o3 [  N" @6 ?    prediction = model(test_input, training=True)% `- U  ~4 ~) H& n7 V4 i
    plt.figure(figsize=(15,15))2 f6 ~, a) a- O
    display_list = [test_input[0], tar[0], prediction[0]]
7 e/ t6 W2 R5 ?  R! z% o+ o- ?    title = ['Input', 'Target', 'Predicted']
6 h0 v' n; J6 j* V. o& l- ^2 l5 w' T    for i in range(3):# @7 R1 Z8 \1 b
        plt.subplot(1, 3, i+1)2 i2 A% O$ F/ `: m$ ?. n
        plt.title(title)
: B' X& q3 b( C2 ]0 ^        plt.imshow(tensor_to_array(display_list) * 0.5 + 0.5)# k% L) Y, w) t7 w) {9 G, h* Q
        plt.axis('off')
1 J* \% C9 Z7 t5 g% O( x9 U) p    plt.show()5 ~2 m( w* L; a; {
ckpt_manager = tf.train.CheckpointManager(checkpoint, "./", max_to_keep=2)# p8 \& L5 T  Z. v) M
if ckpt_manager.latest_checkpoint:* e+ K: v. {1 r! @
    checkpoint.restore(ckpt_manager.latest_checkpoint)
) A( B% O, f9 Q' K" A2 i# |for inp, tar in test_dataset.take(20):
2 j8 X4 o& @' X/ @2 y' `' q; y5 F  E. y    generate_images(generator, inp, tar)$ n# {. r4 L/ T! B5 P# K  m- Z$ K" c

- p1 c0 z3 ^% H) v; P5 B: k第九步: 训练( ]  m: D( I- A
在训练中,我们输出第一张图片来查看每个epoch给我们的预测结果带来的变化。让大家感受到其中的乐趣
1 m1 ?6 O6 C) p" I每20个epoch我们保存一次状态7 K" D' g+ J$ }8 m0 {# q
@tf.function. p. ?/ v; I% k! z, e5 S0 K3 Z! P5 K; b
def train_step(input_image, target):: e$ P4 o) O7 T! I7 |, N
    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
: u. M3 ?* y; ~- z3 K+ F1 _  A3 P        gen_output = generator(input_image, training=True)
/ O2 B: J, k8 O% K( L        disc_real_output = discriminator([input_image, target], training=True)
2 o6 |) s$ }9 D7 @( L        disc_generated_output = discriminator([input_image, gen_output], training=True)
3 J* J, u% t' F9 Y9 \        gen_loss = generator_loss(disc_generated_output, gen_output, target)8 V% _! [0 x/ |+ o2 W- ?
        disc_loss = discriminator_loss(disc_real_output, disc_generated_output)
5 R2 |' B8 H' F  x1 j& Y$ d( }1 g    generator_gradients = gen_tape.gradient(gen_loss,& M0 R/ O8 [) X5 ~$ d" \
                                          generator.trainable_variables)
* j9 L$ B" q! e9 U, F    discriminator_gradients = disc_tape.gradient(disc_loss,. ]% K9 \; I5 z$ p4 E
                                               discriminator.trainable_variables)& _8 @* d4 ?& S0 A& U& R
    generator_optimizer.apply_gradients(zip(generator_gradients,
, X- g9 k+ c6 p6 w7 m8 M- H                                          generator.trainable_variables)); l% D# J9 m' y- {- M$ @9 {
    discriminator_optimizer.apply_gradients(zip(discriminator_gradients,
) ]8 z0 G; Y. l* l: x2 E9 l% n) x# ^1 w                                              discriminator.trainable_variables))' F, Y7 z' o+ }9 ?: z3 I0 A
def fit(train_ds, epochs, test_ds):5 Q& b9 N* @- y+ g* [$ a1 o' m
    for epoch in range(epochs):6 P- i& w  g' F  _5 g) e% O0 x
        start = time.time()
. ]' r. o3 @0 [+ x) G" X# ~        for input_image, target in train_ds:8 t% _" k0 c% f* v- C2 t# t
            train_step(input_image, target)
/ }4 Q) \5 [, k. ?) n5 k        clear_output(wait=True)
1 f) K- x8 N. v      
% c2 K1 O1 ]* j        for example_input, example_target in test_ds.take(1):; r& X+ }: w' M$ {0 D1 R9 U
            generate_images(generator, example_input, example_target)
+ d" H0 ^5 o# B7 q7 S$ J8 t        if (epoch + 1) % 20 == 0:+ q1 {: e$ ~9 C* [+ X7 q: l& ^) l
            ckpt_save_path = ckpt_manager.save()
* q% l, B6 [4 k# t; t" F3 g, A4 K0 l            print ('保存第{}个epoch到{}\n'.format(epoch+1, ckpt_save_path))& I! E/ w, t  W. E2 N
        print ('训练第{}个epoch所用的时间为{:.2f}秒\n'.format(epoch + 1, time.time()-start))
# [# N. Y9 ~# y; V# J; _fit(train_dataset, EPOCHS, test_dataset)
$ `$ {, r) Z) c! F* L/ e4 P$ M3 [6 G+ g. i; K9 E( x6 ?3 b5 V5 I
训练第8个epoch所用的时间为51.33秒。1 c- ?2 @( {& Q
第十步: 使用测试数据上色,查看下我们的效果
2 C/ a$ {) x% X' [for input, target in test_dataset.take(20):2 R! }: y$ {( e6 W" G$ y! q3 l. x5 f
    generate_images(generator, input, target)
2 Q7 e+ _8 r- U# P+ F( O' l矩池云现在已经上架 “口袋妖怪上色” 镜像;感兴趣的小伙伴可以通过矩池云官网“Jupyter 教程 Demo” 镜像中尝试使用。
- w" Z; Z3 \1 L5 {2 u9 [& {
BitMere.com 比特池塘系信息发布平台,比特池塘仅提供信息存储空间服务。
声明:该文观点仅代表作者本人,本文不代表比特池塘立场,且不构成建议,请谨慎对待。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

成为第一个吐槽的人

阿丽66 小学生
  • 粉丝

    0

  • 关注

    0

  • 主题

    2