需要脚本演示、定制部署或海外获客方案?访问 Facebook18 官网
首页 / twitter引流推广

推特点赞评论(推特怎么看点赞最多的评论)

2023-01-29twitter引流推广静态 HTML 文章

未标题-1-4 (1).png

铜灵 发自 凹非寺

量子位 出品| 公众号 QbitAI

CycleGAN,一个可以将一张图像的特征迁移到另一张图像的酷算法,此前可以完成马变斑马、冬天变夏天、苹果变桔子等一颗赛艇的效果。

这行被顶会ICCV收录的研究自提出后,就为图形学等领域的技术人员所用,甚至还成为不少艺术家用来创作的工具。

也是目前大火的“换脸”技术的老前辈了。

如果你还没学会这项厉害的研究,那这次一定要抓紧上车了。

现在,TensorFlow开始手把手教你,在TensorFlow 2.0中CycleGAN实现大法。

这个官方教程贴几天内收获了满满人气,获得了Google AI工程师、哥伦比亚大学数据科学研究所Josh Gordon的推荐,推特上已近600赞。

有国外网友称赞太棒,表示很高兴看到TensorFlow 2.0教程中涵盖了蕞先进的模型。

这份教程全面详细,想学CycleGAN不能错过这个:

详细内容

在TensorFlow 2.0中实现CycleGAN,只要7个步骤就可以了。

1、设置输入Pipeline

安装tensorflow_examples包,用于导入生成器和鉴别器。

!pip install -q git+https://github.com/tensorflow/examples.git

!pip install -q tensorflow-gpu==2.0.0-beta1import tensorflow as tffrom __future__ import absolute_import, division, print_function, unicode_literalsimport tensorflow_datasets as tfdsfrom tensorflow_examples.models.pix2pix import pix2piximport osimport timeimport matplotlib.pyplot as pltfrom IPython.display import clear_outputtfds.disable_progress_barAUTOTUNE = tf.data.experimental.AUTOTUNE

2、输入pipeline

在这个教程中,我们主要学习马到斑马的图像转换,如果想寻找类似的数据集,可以前往:

https://www.tensorflow.org/datasets/datasets#cycle_gan

在CycleGAN论文中也提到,将随机抖动和镜像应用到训练集中,这是避免过度拟合的图像增强技术。

和在Pix2Pix中的操作类似,在随机抖动中吗,图像大小被调整成286×286,然后随机裁剪为256×256。

在随机镜像中吗,图像随机水平翻转,即从左到右进行翻转。

dataset, metadata = tfds.loadtrain_horses, train_zebras = dataset[\’trainA\’], dataset[\’trainB\’]test_horses, test_zebras = dataset[\’testA\’], dataset[\’testB\’]

BUFFER_SIZE = 1000BATCH_SIZE = 1IMG_WIDTH = 256IMG_HEIGHT = 256def random_crop: cropped_image = tf.image.random_crop return cropped_image

# normalizing the images to [-1, 1]def normalize: image = tf.cast image = – 1 return image

def random_jitter: # resizing to 286 x 286 x 3 image = tf.image.resize # randomly cropping to 256 x 256 x 3 image = random_crop # random mirroring image = tf.image.random_flip_left_right return image

def preprocess_image_train: image = random_jitter image = normalize return image

def preprocess_image_test: image = normalize return image

train_horses = train_horses.map.cache.shuffle.batchtrain_zebras = train_zebras.map.cache.shuffle.batchtest_horses = test_horses.map.cache.shuffle.batchtest_zebras = test_zebras.map.cache.shuffle.batch

sample_horse = next)sample_zebra = next)

plt.subplotplt.titleplt.imshowplt.subplotplt.titleplt.imshow * 0.5 + 0.5)

plt.subplotplt.titleplt.imshowplt.subplotplt.titleplt.imshow * 0.5 + 0.5)

3、导入并重新使用Pix2Pix模型

通过安装tensorflow_examples包,从Pix2Pix中导入生成器和鉴别器。

这个教程中使用的模型体系结构与Pix2Pix中很类似,但也有一些差异,比如Cyclegan使用的是实例规范化而不是批量规范化,比如Cyclegan论文使用的是修改后的resnet生成器等。

我们训练两个生成器和两个鉴别器。生成器G架构图像X转换为图像Y,生成器F将图像Y转换为图像X。

鉴别器D_X区分图像X和生成的图像X),辨别器D_Y区分图像Y和生成的图像Y)。

OUTPUT_CHANNELS = 3generator_g = pix2pix.unet_generatorgenerator_f = pix2pix.unet_generatordiscriminator_x = pix2pix.discriminatordiscriminator_y = pix2pix.discriminator

to_zebra = generator_gto_horse = generator_fplt.figure)contrast = 8plt.subplotplt.titleplt.imshowplt.subplotplt.titleplt.imshowplt.subplotplt.titleplt.imshowplt.subplotplt.titleplt.imshowplt.show

plt.figure)plt.subplotplt.titleplt.imshow[0, …, -1], cmap=\’RdBu_r\’)plt.subplotplt.titleplt.imshow[0, …, -1], cmap=\’RdBu_r\’)plt.show

4、损失函数

在CycleGAN中,因为没有用于训练的成对数据,因此无法保证输入X和目标Y在训练期间是否有意义。因此,为了强制学习正确的映射,CycleGAN中提出了“循环一致性损失”。

鉴别器和生成器的损失与Pix2Pix中的类似。

LAMBDA = 10

loss_obj = tf.keras.losses.BinaryCrossentropy

def discriminator_loss: real_loss = loss_obj, real) generated_loss = loss_obj, generated) total_disc_loss = real_loss + generated_loss return total_disc_loss * 0.5

def generator_loss: return loss_obj, generated)

循环一致性意味着结果接近原始输入。

例如将一个句子和英语翻译成法语,再将其从法语翻译成英语后,结果与原始英文句子相同。

在循环一致性损失中,图像X通过生成器传递C产生的图像Y^,生成的图像Y^通过生成器传递F产生的图像X^,然后计算平均绝对误差X和X^。

前向循环一致性损失为:

反向循环一致性损失为:

def calc_cycle_loss: loss1 = tf.reduce_mean) return LAMBDA * loss1

初始化所有生成器和鉴别器的的优化:

generator_g_optimizer = tf.keras.optimizers.Adamgenerator_f_optimizer = tf.keras.optimizers.Adamdiscriminator_x_optimizer = tf.keras.optimizers.Adamdiscriminator_y_optimizer = tf.keras.optimizers.Adam

5、检查点

checkpoint_path = \\\”./checkpoints/train\\\”ckpt = tf.train.Checkpointckpt_manager = tf.train.CheckpointManager# if a checkpoint exists, restore the latest checkpoint.if ckpt_manager.latest_checkpoint: ckpt.restore print

6、训练

注意:为了使本教程的训练时间合理,本示例模型迭代次数较少,预测效果可能不如论文准确。

EPOCHS = 40

def generate_images: prediction = model plt.figure) display_list = [test_input[0], prediction[0]] title = [\’Input Image\’, \’Predicted Image\’] for i in range: plt.subplot plt.title # getting the pixel values between [0, 1] to plot it. plt.imshow plt.axis plt.show

尽管训练起来很复杂,但基本的步骤只有四个,分别为:获取预测、计算损失、使用反向传播计算梯度、将梯度应用于优化程序。

@tf.functiondef train_step: # persistent is set to True because gen_tape and disc_tape is used more than # once to calculate the gradients. with tf.GradientTape as gen_tape, tf.GradientTape as disc_tape: fake_y = generator_g cycled_x = generator_f fake_x = generator_f cycled_y = generator_g disc_real_x = discriminator_x disc_real_y = discriminator_y disc_fake_x = discriminator_x disc_fake_y = discriminator_y # calculate the loss gen_g_loss = generator_loss gen_f_loss = generator_loss # Total generator loss = adversarial loss + cycle loss total_gen_g_loss = gen_g_loss + calc_cycle_loss total_gen_f_loss = gen_f_loss + calc_cycle_loss disc_x_loss = discriminator_loss disc_y_loss = discriminator_loss # Calculate the gradients for generator and discriminator generator_g_gradients = gen_tape.gradient generator_f_gradients = gen_tape.gradient discriminator_x_gradients = disc_tape.gradient discriminator_y_gradients = disc_tape.gradient # Apply the gradients to the optimizer generator_g_optimizer.apply_gradients) generator_f_optimizer.apply_gradients) discriminator_x_optimizer.apply_gradients) discriminator_y_optimizer.apply_gradients)

for epoch in range: start = time.time n = 0 for image_x, image_y in tf.data.Dataset.zip): train_step if n % 10 == 0: print n+=1 clear_output # Using a consistent image so that the progress of the model # is clearly visible. generate_images if % 5 == 0: ckpt_save_path = ckpt_manager.save print ) print -start))

7、使用测试集生成图像

# Run the trained model on the test datasetfor inp in test_horses.take: generate_images

8、进阶学习方向

在上面的教程中,我们学习了如何从Pix2Pix中实现的生成器和鉴别器进一步实现CycleGAN,接下来的学习你可以尝试使用TensorFlow中的其他数据集。

你还可以用更多次的迭代改善结果,或者实现论文中修改的ResNet生成器,进行知识点的进一步巩固。

传送门

https://www.tensorflow.org/beta/tutorials/generative/cyclegan

GitHub地址:

https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/generative/cyclegan.ipynb

— 完 —

诚挚招聘

量子位正在招募编辑/记者,工作地点在北京中关村。期待有才气、有热情的同学加入我们!相关细节,请在量子位公众号对话界面,回复“招聘”两个字。

量子位 QbitAI · 头条号签约作者

վ\’ᴗ\’ ի 追踪AI技术和产品新动态

海外精品引流脚本–最强海外引流  

官网:www.facebook18.com

唯一TG:https://t.me/Facebook181818

Facebook.png

查看演示与获取方案

读完本篇后,可通过下方入口查看演示视频、联系客服或访问主站。