{"id":36411,"date":"2024-11-01T09:48:16","date_gmt":"2024-11-01T09:48:16","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=36411"},"modified":"2024-11-01T11:00:01","modified_gmt":"2024-11-01T11:00:01","slug":"use-of-pytorch-for-gan-deep-learning-probabilistic-generative-model","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/36411\/","title":{"rendered":"Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model"},"content":{"rendered":"<p><body><\/p>\n<p>In this post, we will take a closer look at <strong>Generative Adversarial Networks (GAN)<\/strong>. GAN is a generative model proposed by Ian Goodfellow in 2014, which uses two neural networks (Generator and Discriminator) to generate data. The key aspect of GAN that we focus on is that the two neural networks compete with each other, which allows for the generation of more advanced data.<\/p>\n<h2>1. Basic Structure of GAN<\/h2>\n<p>GAN consists of the following two components:<\/p>\n<ul>\n<li><strong>Generator<\/strong>: It is responsible for generating new data. It takes random noise as input and outputs data that is similar to real data.<\/li>\n<li><strong>Discriminator<\/strong>: It distinguishes whether the given data is real data or data generated by the Generator.<\/li>\n<\/ul>\n<p>The Generator and Discriminator are trained through the following loss functions:<\/p>\n<ul>\n<li><strong>Generator Loss Function<\/strong>: It encourages the Discriminator to classify the output of the Generator as real data.<\/li>\n<li><strong>Discriminator Loss Function<\/strong>: It learns to distinguish between the distribution of real data and data generated by the Generator as much as possible.<\/li>\n<\/ul>\n<h2>2. Training Process of GAN<\/h2>\n<p>The training process of the GAN model consists of the following steps:<\/p>\n<ol>\n<li>Select a random sample from the real dataset.<\/li>\n<li>Generate fake data by inputting random noise into the Generator.<\/li>\n<li>Feed the Discriminator with both real and fake data, calculating their respective probabilities.<\/li>\n<li>Update the Generator and Discriminator based on their respective loss functions.<\/li>\n<li>Repeat this process.<\/li>\n<\/ol>\n<h2>3. Implementing GAN Using PyTorch<\/h2>\n<p>Now, let&#8217;s implement a simple GAN using PyTorch. In this example, we will implement a GAN model that generates digit images using the MNIST dataset.<\/p>\n<h3>3.1 Installing Required Libraries<\/h3>\n<pre><code>\n# Install required libraries\n!pip install torch torchvision matplotlib\n<\/code><\/pre>\n<h3>3.2 Loading and Preprocessing the Dataset<\/h3>\n<pre><code>\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\n\n# Download and preprocess the MNIST dataset\ntransform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])\ntrain_set = torchvision.datasets.MNIST(root='.\/data', train=True, download=True, transform=transform)\ntrain_loader = torch.utils.data.DataLoader(train_set, batch_size=64, shuffle=True)\n<\/code><\/pre>\n<h3>3.3 Defining Generator and Discriminator Models<\/h3>\n<pre><code>\nimport torch.nn as nn\n\n# Define Generator model\nclass Generator(nn.Module):\n    def __init__(self):\n        super(Generator, self).__init__()\n        self.fc = nn.Sequential(\n            nn.Linear(100, 256),\n            nn.ReLU(),\n            nn.Linear(256, 512),\n            nn.ReLU(),\n            nn.Linear(512, 1024),\n            nn.ReLU(),\n            nn.Linear(1024, 28 * 28),\n            nn.Tanh(),\n        )\n\n    def forward(self, x):\n        x = self.fc(x)\n        return x.view(-1, 1, 28, 28)\n\n# Define Discriminator model\nclass Discriminator(nn.Module):\n    def __init__(self):\n        super(Discriminator, self).__init__()\n        self.fc = nn.Sequential(\n            nn.Linear(28 * 28, 512),\n            nn.LeakyReLU(0.2),\n            nn.Linear(512, 256),\n            nn.LeakyReLU(0.2),\n            nn.Linear(256, 1),\n            nn.Sigmoid(),\n        )\n\n    def forward(self, x):\n        x = x.view(-1, 28 * 28)\n        return self.fc(x)\n<\/code><\/pre>\n<h3>3.4 Model Training<\/h3>\n<pre><code>\n# Setting hyperparameters\nnum_epochs = 200\nlearning_rate = 0.0002\nbeta1 = 0.5\n\n# Initialize models\ngenerator = Generator()\ndiscriminator = Discriminator()\n\n# Define loss function and optimization algorithm\ncriterion = nn.BCELoss()\noptimizerG = torch.optim.Adam(generator.parameters(), lr=learning_rate, betas=(beta1, 0.999))\noptimizerD = torch.optim.Adam(discriminator.parameters(), lr=learning_rate, betas=(beta1, 0.999))\n\n# Training loop\nfor epoch in range(num_epochs):\n    for i, (data, _) in enumerate(train_loader):\n        # Setting labels for real and fake data\n        real_labels = torch.ones(data.size(0), 1)\n        fake_labels = torch.zeros(data.size(0), 1)\n\n        # Training Discriminator\n        optimizerD.zero_grad()\n        outputs = discriminator(data)\n        lossD_real = criterion(outputs, real_labels)\n        lossD_real.backward()\n\n        noise = torch.randn(data.size(0), 100)\n        fake_data = generator(noise)\n        outputs = discriminator(fake_data.detach())\n        lossD_fake = criterion(outputs, fake_labels)\n        lossD_fake.backward()\n        optimizerD.step()\n\n        # Training Generator\n        optimizerG.zero_grad()\n        outputs = discriminator(fake_data)\n        lossG = criterion(outputs, real_labels)\n        lossG.backward()\n        optimizerG.step()\n\n    if (epoch+1) % 10 == 0:\n        print(f'Epoch [{epoch+1}\/{num_epochs}], Loss D: {lossD_real.item() + lossD_fake.item():.4f}, Loss G: {lossG.item():.4f}')\n<\/code><\/pre>\n<h3>3.5 Visualizing Results<\/h3>\n<pre><code>\n# Function to visualize generated images\ndef visualize(generator):\n    noise = torch.randn(64, 100)\n    fake_data = generator(noise)\n    fake_data = fake_data.detach().numpy()\n    fake_data = (fake_data + 1) \/ 2  # Normalize to [0, 1]\n\n    plt.figure(figsize=(8, 8))\n    for i in range(fake_data.shape[0]):\n        plt.subplot(8, 8, i+1)\n        plt.axis('off')\n        plt.imshow(fake_data[i][0], cmap='gray')\n    plt.show()\n\n# Visualize results\nvisualize(generator)\n<\/code><\/pre>\n<h2>4. Applications of GAN<\/h2>\n<p>GANs are used not only for image generation but also in various fields:<\/p>\n<ul>\n<li><strong>Image Generation<\/strong>: GAN can be used to generate high-quality images.<\/li>\n<li><strong>Style Transfer<\/strong>: GAN can be used to transform the style of an image. For instance, it can convert a daytime photo to nighttime.<\/li>\n<li><strong>Data Augmentation<\/strong>: GAN can be used to augment datasets by generating new data.<\/li>\n<\/ul>\n<h2>5. Conclusion<\/h2>\n<p>In this post, we explored the concept of GAN and a simple implementation method using PyTorch. GAN is a type of generative model with various potential applications. With the current advancements in GANs and various model variations being proposed, learning and utilizing GANs will be a very useful skill.<\/p>\n<p>I hope this post has helped in understanding GAN and aided in practical implementation. I will return with more diverse topics on deep learning in the future!<\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this post, we will take a closer look at Generative Adversarial Networks (GAN). GAN is a generative model proposed by Ian Goodfellow in 2014, which uses two neural networks (Generator and Discriminator) to generate data. The key aspect of GAN that we focus on is that the two neural networks compete with each other, &hellip; <a href=\"https:\/\/atmokpo.com\/w\/36411\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[113],"tags":[],"class_list":["post-36411","post","type-post","status-publish","format-standard","hentry","category-gan-deep-learning-course"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/36411\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"In this post, we will take a closer look at Generative Adversarial Networks (GAN). GAN is a generative model proposed by Ian Goodfellow in 2014, which uses two neural networks (Generator and Discriminator) to generate data. The key aspect of GAN that we focus on is that the two neural networks compete with each other, &hellip; \ub354 \ubcf4\uae30 &quot;Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/36411\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:48:16+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:00:01+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"4\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/36411\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36411\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model\",\"datePublished\":\"2024-11-01T09:48:16+00:00\",\"dateModified\":\"2024-11-01T11:00:01+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36411\/\"},\"wordCount\":421,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"GAN deep learning course\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/36411\/\",\"url\":\"https:\/\/atmokpo.com\/w\/36411\/\",\"name\":\"Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:48:16+00:00\",\"dateModified\":\"2024-11-01T11:00:01+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36411\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/36411\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/36411\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/36411\/","og_locale":"ko_KR","og_type":"article","og_title":"Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"In this post, we will take a closer look at Generative Adversarial Networks (GAN). GAN is a generative model proposed by Ian Goodfellow in 2014, which uses two neural networks (Generator and Discriminator) to generate data. The key aspect of GAN that we focus on is that the two neural networks compete with each other, &hellip; \ub354 \ubcf4\uae30 \"Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model\"","og_url":"https:\/\/atmokpo.com\/w\/36411\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:48:16+00:00","article_modified_time":"2024-11-01T11:00:01+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"4\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/36411\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/36411\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model","datePublished":"2024-11-01T09:48:16+00:00","dateModified":"2024-11-01T11:00:01+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/36411\/"},"wordCount":421,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["GAN deep learning course"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/36411\/","url":"https:\/\/atmokpo.com\/w\/36411\/","name":"Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:48:16+00:00","dateModified":"2024-11-01T11:00:01+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/36411\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/36411\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/36411\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Use of PyTorch for GAN Deep Learning, Probabilistic Generative Model"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36411","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=36411"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36411\/revisions"}],"predecessor-version":[{"id":36412,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36411\/revisions\/36412"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=36411"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=36411"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=36411"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}