1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
| import glob
import numpy as np import io
from PIL import Image import tensorflow as tf import matplotlib.pyplot as plt from tensorflow import keras from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics from tensorflow_core.python.keras import regularizers import multiprocessing
BATCH_SIZE = 512 CODE_SIZE = 300 LEARNING_RATE = 0.0002 EPOCHS = 2000000
def make_anime_dataset(img_paths, batch_size, resize=64, drop_remainder=True, shuffle=True, repeat=1): @tf.function def _map_fn(img): img = tf.image.resize(img, [resize, resize]) img = tf.clip_by_value(img, 0, 255) img = img / 127.5 - 1 return img
dataset = disk_image_batch_dataset(img_paths, batch_size, drop_remainder=drop_remainder, map_fn=_map_fn, shuffle=shuffle, repeat=repeat) img_shape = (resize, resize, 3) len_dataset = len(img_paths) // batch_size
return dataset, img_shape, len_dataset
def batch_dataset(dataset, batch_size, drop_remainder=True, n_prefetch_batch=1, filter_fn=None, map_fn=None, n_map_threads=None, filter_after_map=False, shuffle=True, shuffle_buffer_size=None, repeat=None): if n_map_threads is None: n_map_threads = multiprocessing.cpu_count() if shuffle and shuffle_buffer_size is None: shuffle_buffer_size = max(batch_size * 128, 2048)
if shuffle: dataset = dataset.shuffle(shuffle_buffer_size)
if not filter_after_map: if filter_fn: dataset = dataset.filter(filter_fn)
if map_fn: dataset = dataset.map(map_fn, num_parallel_calls=n_map_threads)
else: if map_fn: dataset = dataset.map(map_fn, num_parallel_calls=n_map_threads)
if filter_fn: dataset = dataset.filter(filter_fn)
dataset = dataset.batch(batch_size, drop_remainder=drop_remainder)
dataset = dataset.repeat(repeat).prefetch(n_prefetch_batch)
return dataset
def memory_data_batch_dataset(memory_data, batch_size, drop_remainder=True, n_prefetch_batch=1, filter_fn=None, map_fn=None, n_map_threads=None, filter_after_map=False, shuffle=True, shuffle_buffer_size=None, repeat=None): """Batch dataset of memory data.
Parameters ---------- memory_data : nested structure of tensors/ndarrays/lists
""" dataset = tf.data.Dataset.from_tensor_slices(memory_data) dataset = batch_dataset(dataset, batch_size, drop_remainder=drop_remainder, n_prefetch_batch=n_prefetch_batch, filter_fn=filter_fn, map_fn=map_fn, n_map_threads=n_map_threads, filter_after_map=filter_after_map, shuffle=shuffle, shuffle_buffer_size=shuffle_buffer_size, repeat=repeat) return dataset
def disk_image_batch_dataset(img_paths, batch_size, labels=None, drop_remainder=True, n_prefetch_batch=1, filter_fn=None, map_fn=None, n_map_threads=None, filter_after_map=False, shuffle=True, shuffle_buffer_size=None, repeat=None): """Batch dataset of disk image for PNG and JPEG.
Parameters ---------- img_paths : 1d-tensor/ndarray/list of str labels : nested structure of tensors/ndarrays/lists
""" if labels is None: memory_data = img_paths else: memory_data = (img_paths, labels)
def parse_fn(path, *label): img = tf.io.read_file(path) img = tf.image.decode_png(img, 3) return (img,) + label
if map_fn: def map_fn_(*args): return map_fn(*parse_fn(*args)) else: map_fn_ = parse_fn
dataset = memory_data_batch_dataset(memory_data, batch_size, drop_remainder=drop_remainder, n_prefetch_batch=n_prefetch_batch, filter_fn=filter_fn, map_fn=map_fn_, n_map_threads=n_map_threads, filter_after_map=filter_after_map, shuffle=shuffle, shuffle_buffer_size=shuffle_buffer_size, repeat=repeat)
return dataset
discriminator = Sequential([ layers.Conv2D(64, kernel_size=[5, 5], padding="same", strides=3, activation=tf.nn.leaky_relu), layers.BatchNormalization(), layers.Conv2D(128, kernel_size=[5, 5], padding="same", strides=3, activation=tf.nn.leaky_relu), layers.BatchNormalization(), layers.Conv2D(256, kernel_size=[5, 5], padding="same", strides=3, activation=tf.nn.leaky_relu), layers.BatchNormalization(), layers.Flatten(), layers.Dense(128, activation=tf.nn.leaky_relu), layers.Dense(64, activation=tf.nn.leaky_relu), layers.Dense(32, activation=tf.nn.leaky_relu), layers.Dense(16, activation=tf.nn.leaky_relu), layers.Dense(1) ])
generator = Sequential([ layers.Dense(3 * 3 * 512, activation=tf.nn.leaky_relu), layers.Reshape((3, 3, 512)), layers.Conv2DTranspose(256, 3, 3, 'valid', activation=tf.nn.leaky_relu), layers.BatchNormalization(), layers.Conv2DTranspose(128, 5, 2, 'valid', activation=tf.nn.leaky_relu), layers.BatchNormalization(), layers.Conv2DTranspose(3, 4, 3, 'valid', activation=tf.tanh),
])
def save_images(imgs, name): new_im = Image.new('RGB', (640, 640))
index = 0 for i in range(0, 640, 64): for j in range(0, 640, 64): im = imgs[index] im = np.array(im) im = ((im + 1.0) * 127.5).astype(np.uint8) im = Image.fromarray(im, mode='RGB') new_im.paste(im, (i, j)) index += 1
new_im.save(name)
def gradient_penalty(discriminator, batch_x, fake_images): t = tf.random.uniform([BATCH_SIZE, 1, 1, 1]) t = tf.broadcast_to(t, batch_x.shape) interplate = t * batch_x + (1 - t) * fake_images with tf.GradientTape() as tape: tape.watch([interplate]) out = discriminator(interplate) grads = tape.gradient(out, interplate) grads = tf.reshape(grads, [BATCH_SIZE, -1]) gp = tf.norm(grads, axis=1) return tf.reduce_mean((gp-1)**2)
def d_loss_fn(generator, discriminator, batch_z, batch_x): fake_images = generator(batch_z) fake_out = discriminator(fake_images) real_out = discriminator(batch_x)
fake_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=fake_out, labels=tf.zeros_like(fake_out)) real_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=real_out, labels=tf.ones_like(real_out))
fake_loss = tf.reduce_mean(fake_loss) real_loss = tf.reduce_mean(real_loss)
gp = gradient_penalty(discriminator, batch_x, fake_images)
return fake_loss + real_loss + gp, gp
img_path = glob.glob(r"E:\BaiduNetdiskDownload\faces\*.jpg") dataset, image_shape, _ = make_anime_dataset(img_path, BATCH_SIZE) dataset = dataset.repeat() db_iter = iter(dataset)
generator.build(input_shape=(None, CODE_SIZE)) discriminator.build(input_shape=(None, 64, 64, 3)) g_optimizer = optimizers.Adam(LEARNING_RATE) d_optimizer = optimizers.Adam(LEARNING_RATE)
def g_loss_fn(generator, discriminator, batch_z): fake_images = generator(batch_z) fake_out = discriminator(fake_images) fake_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=fake_out, labels=tf.ones_like(fake_out)) return tf.reduce_mean(fake_loss)
for epoch in range(EPOCHS): batch_z = tf.random.uniform([BATCH_SIZE, CODE_SIZE], minval=-1, maxval=1) batch_x = next(db_iter)
with tf.GradientTape() as tape: d_loss, gp = d_loss_fn(generator, discriminator, batch_z, batch_x) grads = tape.gradient(d_loss, discriminator.trainable_variables) d_optimizer.apply_gradients(zip(grads, discriminator.trainable_variables))
with tf.GradientTape() as tape: g_loss = g_loss_fn(generator, discriminator, batch_z) grads = tape.gradient(g_loss, generator.trainable_variables) g_optimizer.apply_gradients(zip(grads, generator.trainable_variables))
if epoch % 30 == 0: print("d-loss:", float(d_loss), "g-loss:", float(g_loss), "gp", float(gp)) z = tf.random.uniform([100, CODE_SIZE], minval=-1, maxval=1) images = generator(z) save_images(images, 'w-gan/sampled_epoch%d.png' % epoch) if epoch % 100 == 0: discriminator.save_weights("model-wgan/w-gan-d") generator.save_weights("model-wgan/w-gan-g")
|