しかし (Generative Adversarial Network) は、深層学習内の生成モデリングに対する最先端のアプローチを表し、多くの場合、次のようなアーキテクチャを活用します。 畳み込みニューラル ネットワーク 。生成モデリングの目標は、入力データ内のパターンを自律的に識別し、モデルが元のデータセットに可能な限り似た新しいサンプルを生成できるようにすることです。
この記事では、知っておくべきことをすべて説明します GAN、GAN のアーキテクチャ、GAN の仕組み、GAN モデルの種類など。
目次
- 敵対的生成ネットワークとは何ですか?
- GANの種類
- GAN のアーキテクチャ
- GANはどのように機能するのでしょうか?
- GANの実装
- 敵対的生成ネットワーク (GAN) の応用
- GANの利点
- GANの欠点
- GAN (敵対的生成ネットワーク) - よくある質問
敵対的生成ネットワークとは何ですか?
Generative Adversarial Networks (GAN) は、強力なクラスのニューラル ネットワークであり、 教師なし学習 。 GAN は 2 つで構成されます ニューラルネットワーク 、 弁別器と生成器です。 彼らは敵対的トレーニングを使用して、実際のデータと同一の人工データを生成します。
- Generator は、ランダムなノイズ サンプルを生成することで、作成されたデータと本物のデータを正確に区別する任務を負っている Discriminator を騙そうとします。
- この競争的な相互作用の結果として、現実的で高品質のサンプルが生成され、両方のネットワークが進歩に向けて推進されます。
- GAN は、画像合成、スタイル転送、テキストから画像への合成に広く使用されていることからもわかるように、非常に汎用性の高い人工知能ツールであることが証明されています。
- 彼らはまた、生成モデリングにも革命をもたらしました。
敵対的なトレーニングを通じて、これらのモデルは、ジェネレーターが現実的なサンプルの作成に熟達するまで、競合的な相互作用を行い、約半分の時間でディスクリミネーターを騙します。
Generative Adversarial Networks (GAN) は、次の 3 つの部分に分類できます。
- 原動力: 確率モデルの観点からデータがどのように生成されるかを説明する生成モデルを学習します。
- 敵対的: 「敵対的」という言葉は、ある物事を別の物事に対抗させることを指します。これは、GAN のコンテキストでは、生成結果がデータセット内の実際の画像と比較されることを意味します。ディスクリミネーターとして知られるメカニズムを使用して、本物の画像と偽の画像を区別しようとするモデルが適用されます。
- ネットワーク: トレーニング目的で人工知能 (AI) アルゴリズムとしてディープ ニューラル ネットワークを使用します。
GANの種類
- バニラGAN: これは最も単純なタイプの GAN です。ここで、Generator と Discriminator は単純で基本的なものです。 多層パーセプトロン 。バニラ GAN のアルゴリズムは非常に単純で、次を使用して数式を最適化しようとします。 確率的勾配降下法。
- 条件付き GAN (CGAN): CGAN として説明できます ディープラーニング その方法 いくつかの条件パラメータが配置されます 。
- CGAN では、対応するデータを生成するために追加パラメーター「y」がジェネレーターに追加されます。
- Discriminator が本物のデータと偽の生成データを区別できるように、ラベルも Discriminator への入力に入力されます。
- ディープ畳み込み GAN (DCGAN): DCGAN は、GAN の最も人気があり、最も成功した実装の 1 つです。で構成されています コンブネット 代わりに 多層パーセプトロン 。
- ConvNet は最大プーリングなしで実装されており、実際には畳み込みストライドに置き換えられます。
- また、各層は完全には接続されていません。
- ラプラシアン ピラミッド GAN (LAPGAN): の ラプラシアンピラミッド は、1 オクターブ離れたバンドパス イメージのセットと低周波残差で構成される線形反転イメージ表現です。
- このアプローチ 複数の Generator および Discriminator ネットワークを使用する ラプラシアン ピラミッドのさまざまなレベル。
- このアプローチは、非常に高品質の画像を生成するため、主に使用されます。画像は最初にピラミッドの各層でダウンサンプリングされ、次に逆方向パスで各層で再びアップスケールされ、画像は元のサイズに達するまでこれらの層で条件付き GAN からノイズを取得します。
- 超解像度 GAN (SRGAN): サーガン 名前が示すように、これは GAN を設計する方法です。 ディープニューラルネットワーク 高解像度の画像を生成するために、敵対的ネットワークとともに使用されます。このタイプの GAN は、ネイティブの低解像度画像を最適にアップスケーリングして細部を強調し、その際のエラーを最小限に抑える場合に特に役立ちます。
GAN のアーキテクチャ
Generative Adversarial Network (GAN) は、ジェネレーターとディスクリミネーターという 2 つの主要な部分で構成されます。
発電機モデル
Generative Adversarial Network (GAN) で新鮮で正確なデータを作成する重要な要素は、ジェネレーター モデルです。ジェネレーターはランダム ノイズを入力として受け取り、それをテキストや画像などの複雑なデータ サンプルに変換します。これは通常、ディープ ニューラル ネットワークとして表されます。
トレーニング データの基礎となる分布は、トレーニングを通じて設計内の学習可能なパラメーターのレイヤーによってキャプチャされます。ジェネレーターは出力を調整して、バックプロパゲーションを使用してパラメーターを微調整することによってトレーニングされる際に、実際のデータを厳密に模倣するサンプルを生成します。
ジェネレーターは、ディスクリミネーターをだますことができる高品質で多様なサンプルを生成する能力によって成功します。
発電機の損失
GAN のジェネレーターの目的は、ディスクリミネーターを騙すのに十分なほど現実的な合成サンプルを生成することです。発電機は損失関数を最小限に抑えることでこれを実現します。
どこ、
J_G ジェネレーターがディスクリミネーターをどれだけうまく騙しているかを測定します。- ログ
D(G(z_i) ) は、生成されたサンプルに対して正しい識別器の対数確率を表します。 - ジェネレーターはこの損失を最小限に抑えることを目的としており、ディスクリミネーターが本物として分類するサンプルの生成を促進します。
(log D(G(z_i)) 、1に近い。
弁別器モデル
識別子モデルと呼ばれる人工ニューラル ネットワークは、生成された入力と実際の入力を区別するために敵対的生成ネットワーク (GAN) で使用されます。入力サンプルを評価し、信頼性の確率を割り当てることにより、識別器はバイナリ分類器として機能します。
時間の経過とともに、ディスクリミネーターは、データセットからの本物のデータとジェネレーターによって作成された人工サンプルを区別することを学習します。これにより、パラメータを徐々に磨き、熟練度のレベルを高めることができます。
畳み込み層 画像データを扱うときは、通常、他のモダリティに関連する構造がそのアーキテクチャで使用されます。生成されたサンプルを不正なものとして、本物のサンプルを本物として正確に識別する弁別者の能力を最大限に高めることが、敵対的トレーニング手順の目的です。ジェネレーターとディスクリミネーターの相互作用の結果、ディスクリミネーターのディスクリミネーターはますます強化され、GAN が全体的に非常にリアルな合成データを生成するのに役立ちます。
弁別器の損失
ディスクリミネーターは、生成されたサンプルと実際のサンプルの両方を正しく分類する負の対数の可能性を減らします。この損失により、識別器は、次の方程式を使用して、生成されたサンプルを偽のサンプルと本物のサンプルとして正確に分類するようになります。
J_D 生成されたサンプルと実際のサンプルを識別する識別子の能力を評価します。- 弁別器が実際のデータを正確に分類する対数尤度は、次のように表されます。
logD(x_i) 。 - 弁別器が生成されたサンプルを偽物として正しく分類する対数確率は、次のように表されます。
log(1-D(G(z_i))) 。 - ディスクリミネーターは、人工サンプルと本物のサンプルを正確に識別することで、この損失を減らすことを目的としています。
最小最大損失
Generative Adversarial Network (GAN) では、ミニマックス損失の公式は次のように提供されます。
どこ、
- G はジェネレーター ネットワーク、D はディスクリミネーター ネットワークです。
- 真のデータ分布から得られた実際のデータサンプル
p_{data}(x) はxで表されます。 - 以前のディストリビューションからサンプリングされたランダム ノイズ
p_z(z) (通常は正規分布または一様分布) は z で表されます。 - D(x) は、識別器が実際のデータを実際のものとして正しく識別する可能性を表します。
- D(G(z)) は、識別器が生成器からの生成データを本物であると識別する可能性です。

GANはどのように機能するのでしょうか?
GAN の動作に必要な手順は次のとおりです。
- 初期化: ジェネレーター (G) とディスクリミネーター (D) の 2 つのニューラル ネットワークが作成されます。
- G は、実際のデータによく似た画像やテキストなどの新しいデータを作成するタスクを負います。
- D は批評家として機能し、(トレーニング データセットからの) 実際のデータと G によって生成されたデータを区別しようとします。
- ジェネレーターの最初の動き: G はランダム ノイズ ベクトルを入力として受け取ります。このノイズ ベクトルにはランダムな値が含まれており、G の作成プロセスの開始点として機能します。 G は、内部レイヤーと学習したパターンを使用して、ノイズ ベクトルを、生成された画像などの新しいデータ サンプルに変換します。
- 弁別者のターン: D は 2 種類の入力を受け取ります。
- トレーニング データセットからの実際のデータ サンプル。
- 前のステップで G によって生成されたデータ サンプル。 D の仕事は、各入力を分析し、それが実際のデータなのか、G が作成したものなのかを判断することです。 0 から 1 までの確率スコアを出力します。スコア 1 はデータが本物である可能性が高いことを示し、0 はデータが偽物であることを示します。
- 学習プロセス: ここで、敵対的な部分が登場します。
- D が実際のデータを本物 (1 に近いスコア) として正しく識別し、生成されたデータを偽 (0 に近いスコア) として識別した場合、G と D の両方に少量の報酬が与えられます。それは二人とも自分の仕事をきちんとやっているからだ。
- ただし、重要なのは継続的に改善することです。 D が一貫してすべてを正しく識別する場合、学習することはあまりありません。したがって、最終的には G が D を騙すことが目標となります。
- ジェネレーターの改善:
- D が G の創作物を本物と誤ってラベル付けした場合 (スコアが 1 に近い)、それは G が正しい軌道に乗っている兆候です。この場合、G は重要な肯定的な更新を受け取りますが、D はだまされたことに対するペナルティを受け取ります。
- このフィードバックは、G の生成プロセスを改善して、より現実的なデータを作成するのに役立ちます。
- ディスクリミネーターの適応:
- 逆に、D が G の偽データを正しく識別した (スコアが 0 に近い) にもかかわらず、G が報酬を受け取らなかった場合、D の識別能力はさらに強化されます。
- G と D の間で進行中のこの決闘は、時間の経過とともに両方のネットワークを洗練させます。
トレーニングが進むにつれて、G は現実的なデータを生成するのが上手になり、D が違いを見分けるのが難しくなります。理想的には、G が熟練しすぎて、D が本物のデータと偽のデータを確実に区別できなくなるのです。この時点で、G は十分にトレーニングされていると考えられ、新しい現実的なデータ サンプルを生成するために使用できます。
CSSでテキストを太字にする
敵対的生成ネットワーク (GAN) の実装
GAN がどのように実装されているかを理解するために、次の手順に従って理解していきます。
ステップ 1 : 必要なライブラリをインポートする
Python3
import> torch> import> torch.nn as nn> import> torch.optim as optim> import> torchvision> from> torchvision>import> datasets, transforms> import> matplotlib.pyplot as plt> import> numpy as np> # Set device> device>=> torch.device(>'cuda'> if> torch.cuda.is_available()>else> 'cpu'>)> |
For training on the CIFAR-10 image dataset, this PyTorch module creates a Generative Adversarial Network (GAN), switching between generator and discriminator training. Visualization of the generated images occurs every tenth epoch, and the development of the GAN is tracked. Step 2: Defining a TransformThe code uses PyTorch’s transforms to define a simple picture transforms.Compose. It normalizes and transforms photos into tensors. Python3 # Define a basic transform transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ]) Step 3: Loading the Dataset A CIFAR-10 dataset is created for training with below code, which also specifies a root directory, turns on train mode, downloads if needed, and applies the specified transform. Subsequently, it generates a 32-batch DataLoader and shuffles the training set of data. Python3 train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True) Step 4: Defining parameters to be used in later processes A Generative Adversarial Network (GAN) is used with specified hyperparameters. The latent space’s dimensionality is represented by latent_dim. lr is the optimizer’s learning rate. The coefficients for the Adam optimizer are beta1 and beta2. To find the total number of training epochs, use num_epochs. Python3 # Hyperparameters latent_dim = 100 lr = 0.0002 beta1 = 0.5 beta2 = 0.999 num_epochs = 10 Step 5: Defining a Utility Class to Build the Generator The generator architecture for a GAN in PyTorch is defined with below code. From nn.Module , the Generator class inherits. It is comprised of a sequential model with Tanh, linear, convolutional, batch normalization, reshaping, and upsampling layers. The neural network synthesizes an image (img) from a latent vector (z), which is the generator’s output. The architecture uses a series of learned transformations to turn the initial random noise in the latent space into a meaningful image. Python3 # Define the generator class Generator(nn.Module): def __init__(self, latent_dim): super(Generator, self).__init__() self.model = nn.Sequential( nn.Linear(latent_dim, 128 * 8 * 8), nn.ReLU(), nn.Unflatten(1, (128, 8, 8)), nn.Upsample(scale_factor=2), nn.Conv2d(128, 128, kernel_size=3, padding=1), nn.BatchNorm2d(128, momentum=0.78), nn.ReLU(), nn.Upsample(scale_factor=2), nn.Conv2d(128, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64, momentum=0.78), nn.ReLU(), nn.Conv2d(64, 3, kernel_size=3, padding=1), nn.Tanh() ) def forward(self, z): img = self.model(z) return img Step 6: Defining a Utility Class to Build the Discriminator The PyTorch code describes the discriminator architecture for a GAN. The class Discriminator is descended from nn.Module. It is composed of linear layers, batch normalization, dropout , convolutional, LeakyReLU , and sequential layers. An image (img) is the discriminator’s input, and its validity—the probability that the input image is real as opposed to artificial—is its output. Python3 # Define the discriminator class Discriminator(nn.Module): def __init__(self): super(Discriminator, self).__init__() self.model = nn.Sequential( nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1), nn.LeakyReLU(0.2), nn.Dropout(0.25), nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1), nn.ZeroPad2d((0, 1, 0, 1)), nn.BatchNorm2d(64, momentum=0.82), nn.LeakyReLU(0.25), nn.Dropout(0.25), nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(128, momentum=0.82), nn.LeakyReLU(0.2), nn.Dropout(0.25), nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(256, momentum=0.8), nn.LeakyReLU(0.25), nn.Dropout(0.25), nn.Flatten(), nn.Linear(256 * 5 * 5, 1), nn.Sigmoid() ) def forward(self, img): validity = self.model(img) return validity Step 7: Building the Generative Adversarial Network The code snippet defines and initializes a discriminator (Discriminator) and a generator (Generator). The designated device (GPU if available) receives both models. Binary Cross Entropy Loss, which is frequently used for GANs, is selected as the loss function (adversarial_loss). For the generator (optimizer_G) and discriminator (optimizer_D), distinct Adam optimizers with predetermined learning rates and betas are also defined. Python3 # Define the generator and discriminator # Initialize generator and discriminator generator = Generator(latent_dim).to(device) discriminator = Discriminator().to(device) # Loss function adversarial_loss = nn.BCELoss() # Optimizers optimizer_G = optim.Adam(generator.parameters() , lr=lr, betas=(beta1, beta2)) optimizer_D = optim.Adam(discriminator.parameters() , lr=lr, betas=(beta1, beta2)) Step 8: Training the Generative Adversarial Network For a Generative Adversarial Network (GAN), the code implements the training loop. The training data batches are iterated through during each epoch. Whereas the generator (optimizer_G) is trained to generate realistic images that trick the discriminator, the discriminator (optimizer_D) is trained to distinguish between real and phony images. The generator and discriminator’s adversarial losses are computed. Model parameters are updated by means of Adam optimizers and the losses are backpropagated. Discriminator printing and generator losses are used to track progress. For a visual assessment of the training process, generated images are additionally saved and shown every 10 epochs. Python3 # Training loop for epoch in range(num_epochs): for i, batch in enumerate(dataloader): # Convert list to tensor real_images = batch[0].to(device) # Adversarial ground truths valid = torch.ones(real_images.size(0), 1, device=device) fake = torch.zeros(real_images.size(0), 1, device=device) # Configure input real_images = real_images.to(device) # --------------------- # Train Discriminator # --------------------- optimizer_D.zero_grad() # Sample noise as generator input z = torch.randn(real_images.size(0), latent_dim, device=device) # Generate a batch of images fake_images = generator(z) # Measure discriminator's ability # to classify real and fake images real_loss = adversarial_loss(discriminator (real_images), valid) fake_loss = adversarial_loss(discriminator (fake_images.detach()), fake) d_loss = (real_loss + fake_loss) / 2 # Backward pass and optimize d_loss.backward() optimizer_D.step() # ----------------- # Train Generator # ----------------- optimizer_G.zero_grad() # Generate a batch of images gen_images = generator(z) # Adversarial loss g_loss = adversarial_loss(discriminator(gen_images), valid) # Backward pass and optimize g_loss.backward() optimizer_G.step() # --------------------- # Progress Monitoring # --------------------- if (i + 1) % 100 == 0: print( f'Epoch [{epoch+1}/{num_epochs}] Batch {i+1}/{len(dataloader)} ' f'Discriminator Loss: {d_loss.item():.4f} ' f'Generator Loss: {g_loss.item():.4f}' ) # Save generated images for every epoch if (epoch + 1) % 10 == 0: with torch.no_grad(): z = torch.randn(16, latent_dim, device=device) generated = generator(z).detach().cpu() grid = torchvision.utils.make_grid(generated, nrow=4, normalize=True) plt.imshow(np.transpose(grid, (1, 2, 0))) plt.axis('off') plt.show() Output: Epoch [10/10] Batch 1300/1563 Discriminator Loss: 0.4473 Generator Loss: 0.9555 Epoch [10/10] Batch 1400/1563 Discriminator Loss: 0.6643 Generator Loss: 1.0215 Epoch [10/10] Batch 1500/1563 Discriminator Loss: 0.4720 Generator Loss: 2.5027 GAN Output Application Of Generative Adversarial Networks (GANs)GANs, or Generative Adversarial Networks, have many uses in many different fields. Here are some of the widely recognized uses of GANs: Image Synthesis and Generation : GANs are often used for picture synthesis and generation tasks, They may create fresh, lifelike pictures that mimic training data by learning the distribution that explains the dataset. The development of lifelike avatars, high-resolution photographs, and fresh artwork have all been facilitated by these types of generative networks. Image-to-Image Translation : GANs may be used for problems involving image-to-image translation, where the objective is to convert an input picture from one domain to another while maintaining its key features. GANs may be used, for instance, to change pictures from day to night, transform drawings into realistic images, or change the creative style of an image. Text-to-Image Synthesis : GANs have been used to create visuals from descriptions in text. GANs may produce pictures that translate to a description given a text input, such as a phrase or a caption. This application might have an impact on how realistic visual material is produced using text-based instructions. Data Augmentation : GANs can augment present data and increase the robustness and generalizability of machine-learning models by creating synthetic data samples. Data Generation for Training : GANs can enhance the resolution and quality of low-resolution images. By training on pairs of low-resolution and high-resolution images, GANs can generate high-resolution images from low-resolution inputs, enabling improved image quality in various applications such as medical imaging, satellite imaging, and video enhancement.Advantages of GANThe advantages of the GANs are as follows: Synthetic data generation : GANs can generate new, synthetic data that resembles some known data distribution, which can be useful for data augmentation, anomaly detection, or creative applications. High-quality results : GANs can produce high-quality, photorealistic results in image synthesis, video synthesis, music synthesis, and other tasks. Unsupervised learning : GANs can be trained without labeled data, making them suitable for unsupervised learning tasks, where labeled data is scarce or difficult to obtain. Versatility : GANs can be applied to a wide range of tasks, including image synthesis, text-to-image synthesis, image-to-image translation, anomaly detection , The disadvantages of the GANs are as follows: Training Instability : GANs can be difficult to train, with the risk of instability, mode collapse, or failure to converge. Computational Cost : GANs can require a lot of computational resources and can be slow to train, especially for high-resolution images or large datasets. Overfitting : GANs can overfit the training data, producing synthetic data that is too similar to the training data and lacking diversity. Bias and Fairness : GANs can reflect the biases and unfairness present in the training data, leading to discriminatory or biased synthetic data. Interpretability and Accountability : GANs can be opaque and difficult to interpret or explain, making it challenging to ensure accountability, transparency, or fairness in their applications.GAN(Generative Adversarial Network)- FAQs Q1. What is a Generative Adversarial Network(GAN)?An artificial intelligence model known as a GAN is made up of two neural networks—a discriminator and a generator—that were developed in tandem using adversarial training. The discriminator assesses the new data instances for authenticity, while the generator produces new ones. Q2. What are the main applications of GAN?Generating images and videos, transferring styles, enhancing data, translating images to other images, producing realistic synthetic data for machine learning model training, and super-resolution are just a few of the many uses for GANs. Q3. What challenges do GAN face?GANs encounter difficulties such training instability, mode collapse (when the generator generates a limited range of samples), and striking the correct balance between the discriminator and generator. It’s frequently necessary to carefully build the model architecture and tune the hyperparameters. Q4. How are GAN evaluated?The produced samples’ quality, diversity, and resemblance to real data are the main criteria used to assess GANs. For quantitative assessment, metrics like the Fréchet Inception Distance (FID) and Inception Score are frequently employed. Q5. Can GAN be used for tasks other than image generation ?Yes, different tasks can be assigned to GANs. Text, music, 3D models, and other things have all been generated with them. The usefulness of conditional GANs is expanded by enabling the creation of specific content under certain input conditions. Q6. What are some famous architectures of GANs ?A few well-known GAN architectures are Progressive GAN (PGAN), Wasserstein GAN (WGAN), Conditional GAN (cGAN), Deep Convolutional GAN (DCGAN), and Vanilla GAN. Each has special qualities and works best with particular kinds of data and tasks.>