基于pytorch,编一个GAN的代码
时间: 2024-03-21 07:43:27 浏览: 59
Pytorch实现数字对抗样本生成全套代码(GAN)
5星 · 资源好评率100%
好的,以下是一个简单的GAN代码,用于生成手写数字图像:
```
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.utils.data import DataLoader
# 定义生成器和判别器
class Generator(nn.Module):
def __init__(self, ngf=64):
super(Generator, self).__init__()
self.main = nn.Sequential(
nn.ConvTranspose2d(100, ngf*8, 4, 1, 0, bias=False),
nn.BatchNorm2d(ngf*8),
nn.ReLU(True),
nn.ConvTranspose2d(ngf*8, ngf*4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf*4),
nn.ReLU(True),
nn.ConvTranspose2d(ngf*4, ngf*2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf*2),
nn.ReLU(True),
nn.ConvTranspose2d(ngf*2, ngf, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf),
nn.ReLU(True),
nn.ConvTranspose2d(ngf, 1, 4, 2, 1, bias=False),
nn.Tanh()
)
def forward(self, input):
return self.main(input)
class Discriminator(nn.Module):
def __init__(self, ndf=64):
super(Discriminator, self).__init__()
self.main = nn.Sequential(
nn.Conv2d(1, ndf, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(ndf, ndf*2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf*2),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(ndf*2, ndf*4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf*4),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(ndf*4, ndf*8, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf*8),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(ndf*8, 1, 4, 1, 0, bias=False),
nn.Sigmoid()
)
def forward(self, input):
return self.main(input).view(-1, 1)
# 定义训练函数
def train(netG, netD, dataloader, device, epochs=5, lr=0.0002, beta1=0.5):
criterion = nn.BCELoss()
optimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999))
optimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999))
fixed_noise = torch.randn(64, 100, 1, 1, device=device)
for epoch in range(epochs):
for i, data in enumerate(dataloader, 0):
netD.zero_grad()
real_cpu = data[0].to(device)
b_size = real_cpu.size(0)
label = torch.full((b_size,), 1, device=device)
output = netD(real_cpu)
errD_real = criterion(output, label)
errD_real.backward()
D_x = output.mean().item()
noise = torch.randn(b_size, 100, 1, 1, device=device)
fake = netG(noise)
label.fill_(0)
output = netD(fake.detach())
errD_fake = criterion(output, label)
errD_fake.backward()
D_G_z1 = output.mean().item()
errD = errD_real + errD_fake
optimizerD.step()
netG.zero_grad()
label.fill_(1)
output = netD(fake)
errG = criterion(output, label)
errG.backward()
D_G_z2 = output.mean().item()
optimizerG.step()
print('[%d/%d][%d/%d] Loss_D: %.4f Loss_G: %.4f D(x): %.4f D(G(z)): %.4f / %.4f'
% (epoch+1, epochs, i+1, len(dataloader), errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))
vutils.save_image(real_cpu, '%s/real_samples.png' % "./results", normalize=True)
fake = netG(fixed_noise)
vutils.save_image(fake.detach(), '%s/fake_samples_epoch_%03d.png' % ("./results", epoch+1), normalize=True)
# 加载数据集
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
dataset = dset.MNIST(root="./data", download=True, transform=transform)
dataloader = DataLoader(dataset, batch_size=128, shuffle=True, num_workers=2)
# 训练
device = torch.device("cuda:0" if (torch.cuda.is_available()) else "cpu")
netG = Generator().to(device)
netD = Discriminator().to(device)
train(netG, netD, dataloader, device)
```
这是一个生成手写数字图像的GAN,使用的数据集是MNIST。在训练过程中,生成器和判别器通过对抗的方式互相提升,最终生成器可以生成逼真的手写数字图像。
阅读全文