Can you write me a dcgan model in pytorch
时间: 2024-05-08 07:19:43 浏览: 84
Sure! Here's an example code for a simple DCGAN model in PyTorch:
```python
import torch
import torch.nn as nn
class Generator(nn.Module):
def __init__(self, z_dim=100, img_size=64, ngf=64):
super(Generator, self).__init__()
self.main = nn.Sequential(
# input is a random noise vector z
nn.ConvTranspose2d(z_dim, 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, z):
return self.main(z.view(z.size(0), -1, 1, 1))
class Discriminator(nn.Module):
def __init__(self, img_size=64, ndf=64):
super(Discriminator, self).__init__()
self.main = nn.Sequential(
# input is a 3 x 64 x 64 image
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, x):
return self.main(x).view(-1, 1).squeeze(1)
```
This code defines a generator and a discriminator for DCGAN, which uses a convolutional neural network (CNN) to generate realistic images from random noise. The generator takes a random noise vector as input and produces an image as output, while the discriminator takes an image as input and produces a probability that it is a real image (rather than a generated one). The generator and discriminator are trained together using adversarial loss to optimize for realistic output images.
阅读全文