以下は、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)
クラス 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),