给我基于pytorch的DCGAN代码
时间: 2024-01-21 09:04:26 浏览: 82
以下是基于pytorch的DCGAN代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.utils as vutils
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
# Set random seed for reproducibility
manual_seed = 999
torch.manual_seed(manual_seed)
# Set device to GPU if available, otherwise CPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Define hyperparameters
batch_size = 128
image_size = 64
num_epochs = 100
latent_size = 100
ngf = 64
ndf = 64
lr = 0.0002
beta1 = 0.5
# Load dataset
dataset = dset.CIFAR10(root='./data', download=True,
transform=transforms.Compose([
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
]))
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=2)
# Define generator network
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
self.main = nn.Sequential(
nn.ConvTranspose2d(latent_size, 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, 3, 4, 2, 1, bias=False),
nn.Tanh()
)
def forward(self, input):
output = self.main(input)
return output
# Define discriminator network
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.main = nn.Sequential(
nn.Conv2d(3, 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):
output = self.main(input)
return output.view(-1, 1).squeeze(1)
# Initialize generator and discriminator networks
netG = Generator().to(device)
netD = Discriminator().to(device)
# Initialize generator weights
netG.apply(weights_init)
# Print generator and discriminator architectures
print(netG)
print(netD)
# Define loss function and optimizer
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))
# Define fixed noise for visualization
fixed_noise = torch.randn(64, latent_size, 1, 1, device=device)
# Training loop
for epoch in range(num_epochs):
for i, data in enumerate(dataloader, 0):
# Update discriminator network
netD.zero_grad()
real = data[0].to(device)
batch_size = real.size(0)
label = torch.full((batch_size,), 1, device=device)
output = netD(real)
errD_real = criterion(output, label)
errD_real.backward()
D_x = output.mean().item()
noise = torch.randn(batch_size, latent_size, 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()
# Update generator network
netG.zero_grad()
label.fill_(1)
output = netD(fake)
errG = criterion(output, label)
errG.backward()
D_G_z2 = output.mean().item()
optimizerG.step()
# Print training statistics
if i % 50 == 0:
print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f'
% (epoch, num_epochs, i, len(dataloader),
errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))
# Save generated images for visualization
if (epoch == 0) and (i == 0):
vutils.save_image(real, '%s/real_samples.png' % "./results", normalize=True)
if i % 100 == 0:
with torch.no_grad():
fake = netG(fixed_noise)
vutils.save_image(fake.detach(), '%s/fake_samples_epoch_%03d.png' % ("./results", epoch), normalize=True)
# Save final generator network
torch.save(netG.state_dict(), './generator.pth')
```
阅读全文