当前位置: 首页 > news >正文

制作公司网站哪个好百度指数使用方法

制作公司网站哪个好,百度指数使用方法,下载cmsv7,天门网站网站建设PyTorch深度学习实战#xff08;34#xff09;——Pix2Pix详解与实现 0. 前言1. 模型与数据集1.1 Pix2Pix 基本原理1.2 数据集分析1.3 模型构建策略 2. 实现 Pix2Pix 生成图像小结系列链接 0. 前言 Pix2Pix 是基于生成对抗网络 (Convolutional Generative Adversarial Netwo… PyTorch深度学习实战34——Pix2Pix详解与实现 0. 前言1. 模型与数据集1.1 Pix2Pix 基本原理1.2 数据集分析1.3 模型构建策略 2. 实现 Pix2Pix 生成图像小结系列链接 0. 前言 Pix2Pix 是基于生成对抗网络 (Convolutional Generative Adversarial Networks, GAN) 的图像转换框架能够将输入图像转换为与之对应的输出图像能够广泛用于图像到图像转换的任务如风格转换、图像修复、语义标签到图像的转换等。Pix2Pix 的核心思想是通过对抗训练将输入图像和目标输出图像进行配对使生成网络可以学习到输入图像到输出图像的映射关系。在本节中将学习使用 Pix2Pix 根据给定轮廓生成图像。 1. 模型与数据集 1.1 Pix2Pix 基本原理 Pix2Pix 是基于对抗生成网络 (Convolutional Generative Adversarial Networks, GAN) 的图像转换算法可以将一种图像转换为与之对应的输出图像。例如将黑白线稿转换为彩色图像或将低分辨率图像转换为高分辨率图像等。Pix2Pix 已经被广泛应用于计算机视觉领域例如风格迁移、语义分割、图像去雾等任务。 假设数据集中包含成对的相互关联图像例如线稿图像作为输入实际图像作为输出。如果我们要在给定线稿输入图像的情况下生成图像传统方法中可以将其视为输入到输出的简单映射(即监督学习问题)但传统监督学习只能从历史数据中学习无法为新线稿生成逼真图像。而 GAN 能够在确保生成的图像足够逼真的情况下为新数据样本输出合理预测结果。 1.2 数据集分析 为了训练 Pix2Pix 模型我们需要了解本节所用的数据集数据集取自 berkeley Pix2Pix 数据集可以自行构建数据集也可以下载本文所用数据集下载地址https://pan.baidu.com/s/1a7VE-z1mGWhbIvvst9e8Ng提取码rkvd。数据集包含 4381 张不同样式和颜色的鞋子照片图像尺寸为 256 x 256。 1.3 模型构建策略 在本节中我们将构建 PixPix 模型根据鞋子的手绘轮廓生成鞋子图像模型构建策略如下 获取实际图像并使用 cv2 边缘检测技术创建相应的物体轮廓从原始图像的区块中提取颜色样本以便生成网络预测所需生成的颜色构建 UNet 架构作为生成网络将带有样本区块颜色的轮廓作为输入并预测相应的图像构建判别网络架构获取输入图像并预测它是真实图像还是生成图像训练生成网络和判别网络直到生成网络可以生成欺骗判别网络的生成图像 2. 实现 Pix2Pix 生成图像 接下来使用 PyTorch 实现 Pix2Pix 模型根据给定鞋子轮廓生成图像。 (1) 导入数据集以及所需库 import torch from torch import nn from torch import optim from matplotlib import pyplot as plt import numpy as np from torchvision.utils import make_grid from torch.utils.data import DataLoader, Dataset import cv2 import random from glob import glob # from torch_snippets import * device cuda if torch.cuda.is_available() else cpufrom torchvision import transforms下载后的图像示例如下 在本节中我们需要在给定轮廓(边缘)和鞋子的区块颜色的情况下绘制鞋子。接下来获取给定鞋子图像的边缘然后训练模型根据给定鞋子的轮廓和区块颜色重建鞋子图像。 (2) 定义函数用于从图像中获取边缘 def detect_edges(img):img_gray cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)img_gray cv2.bilateralFilter(img_gray, 5, 50, 50)img_gray_edges cv2.Canny(img_gray, 45, 100)img_gray_edges cv2.bitwise_not(img_gray_edges) # invert black/whiteimg_edges cv2.cvtColor(img_gray_edges, cv2.COLOR_GRAY2RGB)return img_edges在以上代码中利用 OpenCV 中可用的方法获取图像中的边缘。 (3) 定义图像转换管道用于预处理和归一化 IMAGE_SIZE 256preprocess transforms.Compose([transforms.Lambda(lambda x: torch.Tensor(x.copy()).permute(2, 0, 1).to(device)) ])normalize lambda x: (x - 127.5)/127.5(4) 定义数据集类 ShoesData该数据集类返回原始图像和边缘图像。同时我们将随机选择的区块中出现的颜色传递到网络中通过这种方式能够在图像的不同部分添加所需的颜色并生成新图像示例输入(第三张图像)和输出(第一张图像)如下图所示 输入图像是原始鞋子图像(第一张图像)使用原始图像可以提取鞋子的边缘(第二张图像)接下来通过在边缘图像中添加颜色获取输入(第三张图像)-输出(第一张图像)组合。接下来构建 ShoesData 类接受输入轮廓图像添加颜色并返回带有色彩的轮廓图和原始鞋子图像。 定义 ShoesData 类、__init__ 方法和 __len__ 方法 class ShoesData(Dataset):def __init__(self, items):self.items itemsdef __len__(self):return len(self.items)定义 __getitem__ 方法处理输入图像以获取边缘图像然后添加原始图像中存在的颜色。首先获取给定图像的边缘 def __getitem__(self, ix):f self.items[ix]try: im cv2.imread(f, 1)except:blank preprocess(np.ones((IMAGE_SIZE, IMAGE_SIZE, 3), dtypeuint8))return blank, blankedges detect_edges(im)调整图像大小并规范化图像 im, edges cv2.resize(im, (IMAGE_SIZE,IMAGE_SIZE)), cv2.resize(edges, (IMAGE_SIZE,IMAGE_SIZE))im, edges normalize(im), normalize(edges)在边缘图像 edges 上添加颜色并使用函数 preprocess 预处理原始图像和边缘图像 self._draw_color_circles_on_src_img(edges, im)im, edges preprocess(im), preprocess(edges)return edges, im定义添加颜色的函数 def _draw_color_circles_on_src_img(self, img_src, img_target):non_white_coords self._get_non_white_coordinates(img_target)for center_y, center_x in non_white_coords:self._draw_color_circle_on_src_img(img_src, img_target, center_y, center_x)def _get_non_white_coordinates(self, img):non_white_mask np.sum(img, axis-1) 2.75non_white_y, non_white_x np.nonzero(non_white_mask)# randomly sample non-white coordinatesn_non_white len(non_white_y)n_color_points min(n_non_white, 300)idxs np.random.choice(n_non_white, n_color_points, replaceFalse)non_white_coords list(zip(non_white_y[idxs], non_white_x[idxs]))return non_white_coordsdef _draw_color_circle_on_src_img(self, img_src, img_target, center_y, center_x):assert img_src.shape img_target.shape, Image source and target must have same shape.y0, y1, x0, x1 self._get_color_point_bbox_coords(center_y, center_x)color np.mean(img_target[y0:y1, x0:x1], axis(0, 1))img_src[y0:y1, x0:x1] colordef _get_color_point_bbox_coords(self, center_y, center_x):radius 2y0 max(0, center_y-radius1)y1 min(IMAGE_SIZE, center_yradius)x0 max(0, center_x-radius1)x1 min(IMAGE_SIZE, center_xradius)return y0, y1, x0, x1def choose(self):return self[random.randint(len(self))](5) 定义训练、验证数据对应的数据集和数据加载器 from sklearn.model_selection import train_test_split train_items, val_items train_test_split(glob(ShoeV2_photo/*.png), test_size0.2, random_state2) trn_ds, val_ds ShoesData(train_items), ShoesData(val_items)trn_dl DataLoader(trn_ds, batch_size16, shuffleTrue) val_dl DataLoader(val_ds, batch_size16, shuffleTrue)(6) 定义生成网络和判别网络架构利用权重初始化函数 (weights_init_normal)上采样模块 (UNetDown) 和下采样模块 (UNetUp) 定义 GeneratorUNet 和 Discriminator 体系结构。 初始化权重使其服从正态分布 def weights_init_normal(m):classname m.__class__.__name__if classname.find(Conv) ! -1:torch.nn.init.normal_(m.weight.data, 0.0, 0.02)elif classname.find(BatchNorm2d) ! -1:torch.nn.init.normal_(m.weight.data, 1.0, 0.02)torch.nn.init.constant_(m.bias.data, 0.0)定义 UNetwDown 和 UNetUp 类 class UNetDown(nn.Module):def __init__(self, in_size, out_size, normalizeTrue, dropout0.0):super(UNetDown, self).__init__()layers [nn.Conv2d(in_size, out_size, 4, 2, 1, biasFalse)]if normalize:layers.append(nn.InstanceNorm2d(out_size))layers.append(nn.LeakyReLU(0.2))if dropout:layers.append(nn.Dropout(dropout))self.model nn.Sequential(*layers)def forward(self, x):return self.model(x)class UNetUp(nn.Module):def __init__(self, in_size, out_size, dropout0.0):super(UNetUp, self).__init__()layers [nn.ConvTranspose2d(in_size, out_size, 4, 2, 1, biasFalse),nn.InstanceNorm2d(out_size),nn.ReLU(inplaceTrue),]if dropout:layers.append(nn.Dropout(dropout))self.model nn.Sequential(*layers)def forward(self, x, skip_input):x self.model(x)x torch.cat((x, skip_input), 1)return x定义 GeneratorUNet 类 class GeneratorUNet(nn.Module):def __init__(self, in_channels3, out_channels3):super(GeneratorUNet, self).__init__()self.down1 UNetDown(in_channels, 64, normalizeFalse)self.down2 UNetDown(64, 128)self.down3 UNetDown(128, 256)self.down4 UNetDown(256, 512, dropout0.5)self.down5 UNetDown(512, 512, dropout0.5)self.down6 UNetDown(512, 512, dropout0.5)self.down7 UNetDown(512, 512, dropout0.5)self.down8 UNetDown(512, 512, normalizeFalse, dropout0.5)self.up1 UNetUp(512, 512, dropout0.5)self.up2 UNetUp(1024, 512, dropout0.5)self.up3 UNetUp(1024, 512, dropout0.5)self.up4 UNetUp(1024, 512, dropout0.5)self.up5 UNetUp(1024, 256)self.up6 UNetUp(512, 128)self.up7 UNetUp(256, 64)self.final nn.Sequential(nn.Upsample(scale_factor2),nn.ZeroPad2d((1, 0, 1, 0)),nn.Conv2d(128, out_channels, 4, padding1),nn.Tanh(),)def forward(self, x):d1 self.down1(x)d2 self.down2(d1)d3 self.down3(d2)d4 self.down4(d3)d5 self.down5(d4)d6 self.down6(d5)d7 self.down7(d6)d8 self.down8(d7)u1 self.up1(d8, d7)u2 self.up2(u1, d6)u3 self.up3(u2, d5)u4 self.up4(u3, d4)u5 self.up5(u4, d3)u6 self.up6(u5, d2)u7 self.up7(u6, d1)return self.final(u7)定义判别网络类 Discriminator class Discriminator(nn.Module):def __init__(self, in_channels3):super(Discriminator, self).__init__()def discriminator_block(in_filters, out_filters, normalizationTrue):Returns downsampling layers of each discriminator blocklayers [nn.Conv2d(in_filters, out_filters, 4, stride2, padding1)]if normalization:layers.append(nn.InstanceNorm2d(out_filters))layers.append(nn.LeakyReLU(0.2, inplaceTrue))return layersself.model nn.Sequential(*discriminator_block(in_channels * 2, 64, normalizationFalse),*discriminator_block(64, 128),*discriminator_block(128, 256),*discriminator_block(256, 512),nn.ZeroPad2d((1, 0, 1, 0)),nn.Conv2d(512, 1, 4, padding1, biasFalse))def forward(self, img_A, img_B):img_input torch.cat((img_A, img_B), 1)return self.model(img_input)(7) 定义生成网络和判别网络模型对象 from torchsummary import summary generator GeneratorUNet().to(device) discriminator Discriminator().to(device)(8) 定义判别网络训练函数 discriminator_train_step。 判别网络训练函数将源图像 (real_src)、真实图像目标输出 (real_trg)、生成图像目标输出 (fake_trg)、损失函数 (criterion_GAN) 和判别网络优化器 (d_optimizer) 作为输入 def discriminator_train_step(real_src, real_trg, fake_trg, criterion_GAN, d_optimizer):#discriminator.train()d_optimizer.zero_grad()通过比较真实图像的真实值 (real_trg) 和预测值 (real_src) 计算损失 (error_real)其期望判别网络将图像预测为真实图像(由 torch.ones 表示)然后执行反向传播 prediction_real discriminator(real_trg, real_src)error_real criterion_GAN(prediction_real, torch.ones(len(real_src), 1, 16, 16).cuda())error_real.backward()计算与生成图像 (fake_trg) 对应的判别网络损失 (error_fake)其期望判别网络将生成图像目标分类为伪造图像(由 torch.zeros 表示)然后执行反向传播 prediction_fake discriminator(fake_trg.detach(), real_src)error_fake criterion_GAN(prediction_fake, torch.zeros(len(real_src), 1, 16, 16).cuda())error_fake.backward()优化模型权重并返回预测的真实图像和生成图像的总损失 d_optimizer.step()return error_real error_fake(9) 定义函数训练生成网络 (generator_train_step)其获取生成图像目标 (fake_trg) 并进行训练使其在通过判别网络时被识别为生成图像的概率较低 def generator_train_step(real_src, real_trg, fake_trg, criterion_GAN, criterion_pixelwise, lambda_pixel, g_optimizer):#discriminator.train()g_optimizer.zero_grad()prediction discriminator(fake_trg, real_src)loss_GAN criterion_GAN(prediction, torch.ones(len(real_src), 1, 16, 16).cuda())loss_pixel criterion_pixelwise(fake_trg, real_trg)loss_G loss_GAN lambda_pixel * loss_pixelloss_G.backward()g_optimizer.step()return loss_G在以上代码中除了生成网络损失之外我们还获取与给定轮廓的生成图像和真实图像之间的差异相对应的像素损失 (loss_pixel)。 (10) 定义函数获取预测样本 denorm transforms.Normalize((-1, -1, -1), (2, 2, 2)) def sample_prediction():Saves a generated sample from the validation setdata next(iter(val_dl))real_src, real_trg datafake_trg generator(real_src)img_sample torch.cat([denorm(real_src[0]), denorm(fake_trg[0]), denorm(real_trg[0])], -1)img_sample img_sample.detach().cpu().permute(1,2,0).numpy()plt.imshow(img_sample)plt.title(Source::Generated::GroundTruth)plt.show()(11) 对生成网络和判别网络模型对象应用权重初始化函数 (weights_init_normal) generator GeneratorUNet().to(device) discriminator Discriminator().to(device) generator.apply(weights_init_normal) discriminator.apply(weights_init_normal)(12) 指定损失计算方法和优化器 (criteria_GAN 和 criteria_pixelwise) criterion_GAN torch.nn.MSELoss() criterion_pixelwise torch.nn.L1Loss()lambda_pixel 100 g_optimizer torch.optim.Adam(generator.parameters(), lr0.0002, betas(0.5, 0.999)) d_optimizer torch.optim.Adam(discriminator.parameters(), lr0.0002, betas(0.5, 0.999))(13) 训练模型 val_dl DataLoader(val_ds, batch_size1, shuffleTrue)epochs 100 # log Report(epochs) d_loss_epoch [] g_loss_epoch [] for epoch in range(epochs):N len(trn_dl)d_loss_items []g_loss_items []for bx, batch in enumerate(trn_dl):real_src, real_trg batchfake_trg generator(real_src)errD discriminator_train_step(real_src, real_trg, fake_trg, criterion_GAN, d_optimizer)errG generator_train_step(real_src, real_trg, fake_trg, criterion_GAN, criterion_pixelwise, lambda_pixel, g_optimizer)d_loss_items.append(errD.item())g_loss_items.append(errG.item())d_loss_epoch.append(np.average(d_loss_items))g_loss_epoch.append(np.average(g_loss_items))(14) 在样本轮廓图像上生成图像 [sample_prediction() for _ in range(2)]在上图中可以看出模型能够生成与原始图像颜色相似的图像。 小结 Pix2Pix 是强大的图像转换框架通过对抗训练和 U-Net 结构使得生成网络能够将输入图像转换为与之对应的输出图像。同时在训练过程中引入了像素级损失衡量生成图像与目标图像之间的像素级差异促使生成网络生成更加细致和逼真的图像。本节中介绍了 Pix2Pix 的模型训练流程并使用 ShoeV2 数据集训练了一个 Pix2Pix 模型根据边缘图像生成鞋子图像。 系列链接 PyTorch深度学习实战1——神经网络与模型训练过程详解 PyTorch深度学习实战2——PyTorch基础 PyTorch深度学习实战3——使用PyTorch构建神经网络 PyTorch深度学习实战4——常用激活函数和损失函数详解 PyTorch深度学习实战5——计算机视觉基础 PyTorch深度学习实战6——神经网络性能优化技术 PyTorch深度学习实战7——批大小对神经网络训练的影响 PyTorch深度学习实战8——批归一化 PyTorch深度学习实战9——学习率优化 PyTorch深度学习实战10——过拟合及其解决方法 PyTorch深度学习实战11——卷积神经网络 PyTorch深度学习实战12——数据增强 PyTorch深度学习实战13——可视化神经网络中间层输出 PyTorch深度学习实战14——类激活图 PyTorch深度学习实战15——迁移学习 PyTorch深度学习实战16——面部关键点检测 PyTorch深度学习实战17——多任务学习 PyTorch深度学习实战18——目标检测基础 PyTorch深度学习实战19——从零开始实现R-CNN目标检测 PyTorch深度学习实战20——从零开始实现Fast R-CNN目标检测 PyTorch深度学习实战21——从零开始实现Faster R-CNN目标检测 PyTorch深度学习实战22——从零开始实现YOLO目标检测 PyTorch深度学习实战23——使用U-Net架构进行图像分割 PyTorch深度学习实战24——从零开始实现Mask R-CNN实例分割 PyTorch深度学习实战25——自编码器(Autoencoder) PyTorch深度学习实战26——卷积自编码器(Convolutional Autoencoder) PyTorch深度学习实战27——变分自编码器(Variational Autoencoder, VAE) PyTorch深度学习实战28——对抗攻击(Adversarial Attack) PyTorch深度学习实战29——神经风格迁移 PyTorch深度学习实战30——Deepfakes PyTorch深度学习实战31——生成对抗网络(Generative Adversarial Network, GAN) PyTorch深度学习实战32——DCGAN详解与实现 PyTorch深度学习实战33——条件生成对抗网络(Conditional Generative Adversarial Network, CGAN)
http://www.zqtcl.cn/news/559509/

相关文章:

  • 深圳网站建设q.479185700惠哪个网站可以免费设计房子
  • 迁西网站开发网站建设技术网站建
  • 网站建设与管理课程报告能够做外贸的网站有哪些
  • 浅析社区网站的建设如何建立企业网站
  • 网站建设尺寸像素是多少广州商城型网站建设
  • 重庆自助建站模板简述网络营销的特点
  • 企业网站托管一个月多少钱网页设计规范2018
  • 网站建设费用摊销会计分录合肥网站建设哪里好
  • 郑州市建设工程造价信息网站关于工程项目建设的网站
  • 网站做淘宝客收入咋样景区门户网站建设方案
  • 遵义做网站推广西安都有哪些公司
  • 万网建网站流程产品展示网站模板php
  • 新津县建设局网站网站做301
  • 网站域名续费如何建设一个简易网站
  • 网站整体迁移该怎么做wordpress 图片调用api接口
  • 网站获得流量最好的方法是什么 ( )汕头建设学校的网站
  • 网上下载的网站后台安全吗仿系统之家网站源码
  • 网站实名审核高等教材电工学久久建筑网
  • 化学试剂购买网站网站节点加速
  • 桂林城乡建设局网站在线咨询免费
  • 长治网站设计制作网站ps怎么做网站导航内嵌式
  • 网站 橙色前台网站开发
  • 滨海网站建设服务商电子商务网站建设与维护pdf
  • 企业网站建设方案效果h5网页制作app
  • 国内搜索引擎网站免费无线
  • 龙岩做网站价格室内建筑设计
  • 闲鱼上面给人做网站造退款微信登录建设银行网站
  • 无锡网站推广公司网络营销课程设置
  • dede 网站根目录北京好的设计公司
  • 网站关键词重复wordpress 影响力