使用 PyTorch 实现 GAN 的简单例子

下面是使用 PyTorch 实现 GAN 的简单例子。这里假设你已经了解了 GAN 的基本原理,并且安装了 PyTorch。

首先,我们需要定义生成器和判别器。生成器是一个神经网络,它接收随机噪声作为输入,并输出假的图像。判别器是另一个神经网络,它接收图像作为输入,并输出一个值,表示这张图像是否是真实的。

```python import torch import torch.nn as nn import torch.optim as optim

class Generator(nn.Module): def init(self, latent_dim, img_shape): super().init() self.img_shape = img_shape

self.model = nn.Sequential(
        # 输入为随机噪声, 输出为 (batch_size, 128, 4, 4)
        nn.Linear(latent_dim, 128 * 4 * 4),
        nn.BatchNorm1d(128 * 4 * 4),
        nn.LeakyReLU(0.01),
        nn.Reshape(128, 4, 4),
        # 输出为 (batch_size, 128, 8, 8)
        nn.ConvTranspose2d(128, 128, 4, 2, 1),
        nn.BatchNorm2d(128),
        nn.LeakyReLU(0.01),
        # 输出为 (batch_size, 128, 16, 16)
        nn.ConvTranspose2d(128, 128, 4, 2, 1),
        nn.BatchNorm2d(128),
        nn.LeakyReLU(0.01),
        # 输出为 (batch_size, 3, 32, 32)
        nn.ConvTranspose2d(128, 3, 4, 2, 1),
        nn.Tanh()
    )

def forward(self, z):
    return self.model(z)

class Discriminator(nn.Module): def init(self, img_shape): super().init() self.model = nn.Sequential( # 输入为 (batch_size, 3, 32, 32) nn.Conv2d(3, 128, 4, 2, 1),

猜你喜欢

转载自blog.csdn.net/weixin_42609225/article/details/129502144