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

医院网站模板中国国家人事人才培训网官网

医院网站模板,中国国家人事人才培训网官网,职业学院网站建设方案,效果图网站大全文章目录 DCGAN介绍代码结果参考 DCGAN介绍 将CNN和GAN结合起来,把监督学习和无监督学习结合起来。具体解释可以参见 深度卷积对抗生成网络(DCGAN) DCGAN的生成器结构: 图片来源:https://arxiv.org/abs/1511.06434 代码 model.py impor…

文章目录

    • DCGAN介绍
    • 代码
    • 结果
    • 参考

DCGAN介绍

将CNN和GAN结合起来,把监督学习和无监督学习结合起来。具体解释可以参见 深度卷积对抗生成网络(DCGAN)

DCGAN的生成器结构:
在这里插入图片描述
图片来源:https://arxiv.org/abs/1511.06434

代码

model.py

import torch
import torch.nn as nnclass Discriminator(nn.Module):def __init__(self, channels_img, features_d):super(Discriminator, self).__init__()self.disc = nn.Sequential(# Input: N x channels_img x 64 x 64nn.Conv2d(channels_img, features_d, kernel_size=4, stride=2, padding=1), # 32 x 32nn.LeakyReLU(0.2),self._block(features_d, features_d*2, 4, 2, 1), # 16 x 16self._block(features_d*2, features_d*4, 4, 2, 1), # 8 x 8self._block(features_d*4, features_d*8, 4, 2, 1), # 4 x 4nn.Conv2d(features_d*8, 1, kernel_size=4, stride=2, padding=0), # 1 x 1nn.Sigmoid(),)def _block(self, in_channels, out_channels, kernel_size, stride, padding):return nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=False),nn.BatchNorm2d(out_channels),nn.LeakyReLU(0.2),)def forward(self, x):return self.disc(x)class Generator(nn.Module):def __init__(self, z_dim, channels_img, features_g):super(Generator, self).__init__()self.gen = nn.Sequential(# Input: N x z_dim x 1 x 1self._block(z_dim, features_g*16, 4, 1, 0), # N x f_g*16 x 4 x 4self._block(features_g*16, features_g*8, 4, 2, 1), # 8x8self._block(features_g*8, features_g*4, 4, 2, 1), # 16x16self._block(features_g*4, features_g*2, 4, 2, 1), # 32x32nn.ConvTranspose2d(features_g*2, channels_img, kernel_size=4, stride=2, padding=1,),nn.Tanh(),)def _block(self, in_channels, out_channels, kernel_size, stride, padding):return nn.Sequential(nn.ConvTranspose2d(in_channels,out_channels,kernel_size,stride,padding,bias=False,),nn.BatchNorm2d(out_channels),nn.ReLU(),)def forward(self, x):return self.gen(x)def initialize_weights(model):for m in model.modules():if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d, nn.BatchNorm2d)):nn.init.normal_(m.weight.data, 0.0, 0.02)def test():N, in_channels, H, W = 8, 3, 64, 64z_dim = 100x = torch.randn((N, in_channels, H, W))disc = Discriminator(in_channels, 8)initialize_weights(disc)assert disc(x).shape == (N, 1, 1, 1)gen = Generator(z_dim, in_channels, 8)initialize_weights(gen)z = torch.randn((N, z_dim, 1, 1))assert gen(z).shape == (N, in_channels, H, W)print("success")if __name__ == "__main__":test()

训练使用的数据集:CelebA dataset (Images Only) 总共1.3GB的图片,使用方法,将其解压到当前目录

图片如下图所示:
在这里插入图片描述

train.py

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from model import Discriminator, Generator, initialize_weights# Hyperparameters etc.
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
LEARNING_RATE = 2e-4  # could also use two lrs, one for gen and one for disc
BATCH_SIZE = 128
IMAGE_SIZE = 64
CHANNELS_IMG = 3 # 1 if MNIST dataset; 3 if celeb dataset
NOISE_DIM = 100
NUM_EPOCHS = 5
FEATURES_DISC = 64
FEATURES_GEN = 64transforms = transforms.Compose([transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),transforms.ToTensor(),transforms.Normalize([0.5 for _ in range(CHANNELS_IMG)], [0.5 for _ in range(CHANNELS_IMG)]),]
)# If you train on MNIST, remember to set channels_img to 1
# dataset = datasets.MNIST(
#     root="dataset/", train=True, transform=transforms, download=True
# )# comment mnist above and uncomment below if train on CelebA# If you train on celeb dataset, remember to set channels_img to 3
dataset = datasets.ImageFolder(root="celeb_dataset", transform=transforms)
dataloader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)
gen = Generator(NOISE_DIM, CHANNELS_IMG, FEATURES_GEN).to(device)
disc = Discriminator(CHANNELS_IMG, FEATURES_DISC).to(device)
initialize_weights(gen)
initialize_weights(disc)opt_gen = optim.Adam(gen.parameters(), lr=LEARNING_RATE, betas=(0.5, 0.999))
opt_disc = optim.Adam(disc.parameters(), lr=LEARNING_RATE, betas=(0.5, 0.999))
criterion = nn.BCELoss()fixed_noise = torch.randn(32, NOISE_DIM, 1, 1).to(device)
writer_real = SummaryWriter(f"logs/real")
writer_fake = SummaryWriter(f"logs/fake")
step = 0gen.train()
disc.train()for epoch in range(NUM_EPOCHS):# Target labels not needed! <3 unsupervisedfor batch_idx, (real, _) in enumerate(dataloader):real = real.to(device)noise = torch.randn(BATCH_SIZE, NOISE_DIM, 1, 1).to(device)fake = gen(noise)### Train Discriminator: max log(D(x)) + log(1 - D(G(z)))disc_real = disc(real).reshape(-1)loss_disc_real = criterion(disc_real, torch.ones_like(disc_real))disc_fake = disc(fake.detach()).reshape(-1)loss_disc_fake = criterion(disc_fake, torch.zeros_like(disc_fake))loss_disc = (loss_disc_real + loss_disc_fake) / 2disc.zero_grad()loss_disc.backward()opt_disc.step()### Train Generator: min log(1 - D(G(z))) <-> max log(D(G(z))output = disc(fake).reshape(-1)loss_gen = criterion(output, torch.ones_like(output))gen.zero_grad()loss_gen.backward()opt_gen.step()# Print losses occasionally and print to tensorboardif batch_idx % 100 == 0:print(f"Epoch [{epoch}/{NUM_EPOCHS}] Batch {batch_idx}/{len(dataloader)} \Loss D: {loss_disc:.4f}, loss G: {loss_gen:.4f}")with torch.no_grad():fake = gen(fixed_noise)# take out (up to) 32 examplesimg_grid_real = torchvision.utils.make_grid(real[:32], normalize=True)img_grid_fake = torchvision.utils.make_grid(fake[:32], normalize=True)writer_real.add_image("Real", img_grid_real, global_step=step)writer_fake.add_image("Fake", img_grid_fake, global_step=step)step += 1

结果

训练5个epoch,部分结果如下:

Epoch [3/5] Batch 1500/1583                   Loss D: 0.4996, loss G: 1.1738
Epoch [4/5] Batch 0/1583                   Loss D: 0.4268, loss G: 1.6633
Epoch [4/5] Batch 100/1583                   Loss D: 0.4841, loss G: 1.7475
Epoch [4/5] Batch 200/1583                   Loss D: 0.5094, loss G: 1.2376
Epoch [4/5] Batch 300/1583                   Loss D: 0.4376, loss G: 2.1271
Epoch [4/5] Batch 400/1583                   Loss D: 0.4173, loss G: 1.4380
Epoch [4/5] Batch 500/1583                   Loss D: 0.5213, loss G: 2.1665
Epoch [4/5] Batch 600/1583                   Loss D: 0.5036, loss G: 2.1079
Epoch [4/5] Batch 700/1583                   Loss D: 0.5158, loss G: 1.0579
Epoch [4/5] Batch 800/1583                   Loss D: 0.5426, loss G: 1.9427
Epoch [4/5] Batch 900/1583                   Loss D: 0.4721, loss G: 1.2659
Epoch [4/5] Batch 1000/1583                   Loss D: 0.5662, loss G: 2.4537
Epoch [4/5] Batch 1100/1583                   Loss D: 0.5604, loss G: 0.8978
Epoch [4/5] Batch 1200/1583                   Loss D: 0.4085, loss G: 2.0747
Epoch [4/5] Batch 1300/1583                   Loss D: 1.1894, loss G: 0.1825
Epoch [4/5] Batch 1400/1583                   Loss D: 0.4518, loss G: 2.1509
Epoch [4/5] Batch 1500/1583                   Loss D: 0.3814, loss G: 1.9391

使用

tensorboard --logdir=logs

打开tensorboard

在这里插入图片描述

参考

[1] DCGAN implementation from scratch
[2] https://arxiv.org/abs/1511.06434


文章转载自:
http://aweto.gcqs.cn
http://modern.gcqs.cn
http://captaincy.gcqs.cn
http://naxos.gcqs.cn
http://kerf.gcqs.cn
http://armscye.gcqs.cn
http://hexachlorethane.gcqs.cn
http://lacet.gcqs.cn
http://camail.gcqs.cn
http://retractor.gcqs.cn
http://penpoint.gcqs.cn
http://totipalmation.gcqs.cn
http://cosh.gcqs.cn
http://newspaperwoman.gcqs.cn
http://spatted.gcqs.cn
http://aphthongal.gcqs.cn
http://noncontentious.gcqs.cn
http://cider.gcqs.cn
http://cigala.gcqs.cn
http://hurtful.gcqs.cn
http://blinking.gcqs.cn
http://interlaminate.gcqs.cn
http://qbasic.gcqs.cn
http://rheophilous.gcqs.cn
http://prismatic.gcqs.cn
http://absorber.gcqs.cn
http://thornbill.gcqs.cn
http://pancreatectomy.gcqs.cn
http://seism.gcqs.cn
http://cutup.gcqs.cn
http://footrest.gcqs.cn
http://totemist.gcqs.cn
http://tincture.gcqs.cn
http://oxidase.gcqs.cn
http://picnometer.gcqs.cn
http://alternant.gcqs.cn
http://basicity.gcqs.cn
http://pole.gcqs.cn
http://doomful.gcqs.cn
http://intravenous.gcqs.cn
http://forgiveness.gcqs.cn
http://aerocar.gcqs.cn
http://pushiness.gcqs.cn
http://antiwhite.gcqs.cn
http://euryhygric.gcqs.cn
http://scruff.gcqs.cn
http://mule.gcqs.cn
http://derivatively.gcqs.cn
http://hussif.gcqs.cn
http://advisably.gcqs.cn
http://weedless.gcqs.cn
http://distichous.gcqs.cn
http://nugae.gcqs.cn
http://pneumococcus.gcqs.cn
http://cerumen.gcqs.cn
http://biddable.gcqs.cn
http://uncounted.gcqs.cn
http://pretence.gcqs.cn
http://superhelical.gcqs.cn
http://artificiality.gcqs.cn
http://baccivorous.gcqs.cn
http://circumfluence.gcqs.cn
http://carlin.gcqs.cn
http://rodeo.gcqs.cn
http://unplug.gcqs.cn
http://travelogue.gcqs.cn
http://wharfinger.gcqs.cn
http://obstinate.gcqs.cn
http://huebnerite.gcqs.cn
http://natalian.gcqs.cn
http://nyp.gcqs.cn
http://overpower.gcqs.cn
http://pyrolater.gcqs.cn
http://stagnation.gcqs.cn
http://postimpressionism.gcqs.cn
http://giddily.gcqs.cn
http://ovoidal.gcqs.cn
http://lucy.gcqs.cn
http://calumniation.gcqs.cn
http://parsoness.gcqs.cn
http://transvest.gcqs.cn
http://santalin.gcqs.cn
http://hemolysis.gcqs.cn
http://snappish.gcqs.cn
http://advolution.gcqs.cn
http://disallowance.gcqs.cn
http://byobu.gcqs.cn
http://zoophyte.gcqs.cn
http://degerm.gcqs.cn
http://chalutz.gcqs.cn
http://humerus.gcqs.cn
http://addible.gcqs.cn
http://benet.gcqs.cn
http://univac.gcqs.cn
http://forcipressure.gcqs.cn
http://unbroke.gcqs.cn
http://neurological.gcqs.cn
http://casualties.gcqs.cn
http://microevolution.gcqs.cn
http://neuraxitis.gcqs.cn
http://www.15wanjia.com/news/91001.html

相关文章:

  • 织梦网站如何做移动端天津seo推广服务
  • 网站外链怎么发网络推广的工作好做吗
  • 公司注册网站源码网站推广的营销策划方案
  • 网站开发的ui设计全球搜
  • 微网站建设身边的网络营销案例
  • 三项措施做好门户网站建设如何销售自己产品方法有哪些
  • 做物业管理的企业网站杭州百度推广优化排名
  • 成都网站建设科技公seo网站优化优化排名
  • 在线捐款网站开发长春免费网上推广
  • 旅游攻略网站模板按效果付费的网络推广方式
  • 龙华响应式网站建设网络推广的优势
  • 网站建设中药尽量使用图片百度极速版下载安装最新版
  • 用adsl做网站备案重庆seo优
  • 网站如何留住用户西安seo推广公司
  • 做酒店网站有哪些目录品牌营销策略有哪些方法
  • 淘宝内部卷网站怎么做网站建设规划要点详解
  • 永川区网站建设中国市场营销网网站
  • 单页静态网站怎么做百度推广助手客户端
  • 重庆电商网站建设如何建立电商平台
  • 龙华专业做网站公司seo是怎么优化
  • 企业宣传片怎么拍seo和sem是什么意思啊
  • 网泰网站建设体验式营销经典案例
  • 静海的做网站google登录
  • 做暖暖的视频网站在线检测网站安全
  • 阜阳网站开发网站快速收录软件
  • 网站建设果麦科技网络营销与策划
  • 霸气独一无二的公司名字搜索引擎优化的含义和目标
  • 如何在b2b网站做外链重庆森林经典台词 凤梨罐头
  • 股票订阅网站开发冯站长之家官网
  • 企业官网定制设计开发上海百度首页优化