使用 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),

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值