{"id":36485,"date":"2024-11-01T09:48:51","date_gmt":"2024-11-01T09:48:51","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=36485"},"modified":"2024-11-01T11:53:00","modified_gmt":"2024-11-01T11:53:00","slug":"deep-learning-pytorch-course-gan-implementation","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/36485\/","title":{"rendered":"Deep Learning PyTorch Course, GAN Implementation"},"content":{"rendered":"<p><body><\/p>\n<p>In this course, we will provide an in-depth explanation of how to implement GAN (Generative Adversarial Network) using PyTorch. GAN is a tool for training good generative models and is used in various fields such as image generation, style transfer, and data augmentation. The course will start with the basic concepts of GAN, implement each component, and finally help you understand how GAN works through practical examples.<\/p>\n<h2>1. Basic Concepts of GAN<\/h2>\n<p>GAN consists of two main components: the Generator and the Discriminator. These two models learn by competing against each other, which is the core of GAN.<\/p>\n<h3>1.1 Generator<\/h3>\n<p>The role of the generator is to take random noise as input and generate fake data that is similar to real data. This model learns how to mimic real data.<\/p>\n<h3>1.2 Discriminator<\/h3>\n<p>The discriminator serves to distinguish whether the input data is real data or fake data generated by the generator. This model learns how to differentiate between real and fake data.<\/p>\n<h3>1.3 Training Process of GAN<\/h3>\n<p>The training of GAN progresses in a way that the generator and discriminator compete against each other. The generator tries to create increasingly better fake data to fool the discriminator, while the discriminator strives to recognize such fake data. As this process repeats, both models progressively improve.<\/p>\n<h2>2. Implementing Components of GAN<\/h2>\n<p>Now, we will implement the key components necessary to build GAN through coding. Here, we will implement a simple GAN and create a model to generate handwritten digits from the MNIST dataset.<\/p>\n<h3>2.1 Setting Up the Environment<\/h3>\n<p>First, we will install the necessary libraries and download the MNIST dataset to prepare it.<\/p>\n<pre><code>!pip install torch torchvision matplotlib\nimport torch\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\nimport matplotlib.pyplot as plt<\/code><\/pre>\n<h3>2.2 Loading the Dataset<\/h3>\n<p>We load the MNIST dataset and perform preprocessing.<\/p>\n<pre><code># Preparing the dataset\ntransform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])\nmnist = datasets.MNIST(root='.\/data', train=True, download=True, transform=transform)\ndataloader = torch.utils.data.DataLoader(mnist, batch_size=64, shuffle=True)<\/code><\/pre>\n<h3>2.3 Implementing the Generator Model<\/h3>\n<p>The generator is a neural network that takes an input noise vector and transforms it into an image.<\/p>\n<pre><code>import torch.nn as nn\n\nclass Generator(nn.Module):\n    def __init__(self):\n        super(Generator, self).__init__()\n        self.model = 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, z):\n        return self.model(z).view(-1, 1, 28, 28)<\/code><\/pre>\n<h3>2.4 Implementing the Discriminator Model<\/h3>\n<p>The discriminator is a model that determines whether the input image is a real image or a fake image.<\/p>\n<pre><code>class Discriminator(nn.Module):\n    def __init__(self):\n        super(Discriminator, self).__init__()\n        self.model = 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, img):\n        return self.model(img.view(-1, 28 * 28))<\/code><\/pre>\n<h3>2.5 Initializing the Models<\/h3>\n<p>We initialize the generator and discriminator models, define the loss function, and set the optimizer.<\/p>\n<pre><code>generator = Generator()\ndiscriminator = Discriminator()\n\ncriterion = nn.BCELoss()\noptimizer_gen = torch.optim.Adam(generator.parameters(), lr=0.0002, betas=(0.5, 0.999))\noptimizer_disc = torch.optim.Adam(discriminator.parameters(), lr=0.0002, betas=(0.5, 0.999))<\/code><\/pre>\n<h3>2.6 GAN Training Loop<\/h3>\n<p>Next, we will implement the training loop for GAN. We will compute the loss for the generator and the discriminator and update the weights using the optimizer.<\/p>\n<pre><code>def train_gan(num_epochs):\n    for epoch in range(num_epochs):\n        for i, (imgs, _) in enumerate(dataloader):\n            z = torch.randn(imgs.size(0), 100)\n            real_labels = torch.ones(imgs.size(0), 1)\n            fake_labels = torch.zeros(imgs.size(0), 1)\n\n            # Training the discriminator\n            optimizer_disc.zero_grad()\n            outputs = discriminator(imgs)\n            d_loss_real = criterion(outputs, real_labels)\n            d_loss_real.backward()\n\n            fake_imgs = generator(z)\n            outputs = discriminator(fake_imgs.detach())\n            d_loss_fake = criterion(outputs, fake_labels)\n            d_loss_fake.backward()\n            optimizer_disc.step()\n\n            # Training the generator\n            optimizer_gen.zero_grad()\n            outputs = discriminator(fake_imgs)\n            g_loss = criterion(outputs, real_labels)\n            g_loss.backward()\n            optimizer_gen.step()\n\n        if (epoch + 1) % 10 == 0:\n            print(f'Epoch [{epoch + 1}\/{num_epochs}], d_loss: {d_loss_real.item() + d_loss_fake.item():.4f}, g_loss: {g_loss.item():.4f}')<\/code><\/pre>\n<h2>3. Running GAN<\/h2>\n<p>Now, let&#8217;s train the GAN and visualize the generated image results.<\/p>\n<pre><code>num_epochs = 100\ntrain_gan(num_epochs)\n\ndef show_generated_images(generator, num_images=16):\n    z = torch.randn(num_images, 100)\n    fake_images = generator(z).detach()\n    plt.figure(figsize=(10, 10))\n    for i in range(num_images):\n        plt.subplot(4, 4, i + 1)\n        plt.imshow(fake_images[i][0], cmap='gray')\n        plt.axis('off')\n    plt.show()\n\nshow_generated_images(generator)<\/code><\/pre>\n<h2>4. Conclusion<\/h2>\n<p>In this course, we explored the basic concepts of GAN and the process of implementing a simple GAN model using PyTorch. GAN can be applied in various fields such as image generation and style transfer, expanding the possibilities of artificial intelligence. It would also be beneficial to explore more complex variations of GAN based on this course.<\/p>\n<p>This concludes the course on implementing GAN using deep learning with PyTorch. If you have any questions or need more information during the learning process, feel free to ask in the comments!<\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this course, we will provide an in-depth explanation of how to implement GAN (Generative Adversarial Network) using PyTorch. GAN is a tool for training good generative models and is used in various fields such as image generation, style transfer, and data augmentation. The course will start with the basic concepts of GAN, implement each &hellip; <a href=\"https:\/\/atmokpo.com\/w\/36485\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Deep Learning PyTorch Course, GAN Implementation&#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":[149],"tags":[],"class_list":["post-36485","post","type-post","status-publish","format-standard","hentry","category-pytorch-study"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Deep Learning PyTorch Course, GAN Implementation - \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\/36485\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Deep Learning PyTorch Course, GAN Implementation - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"In this course, we will provide an in-depth explanation of how to implement GAN (Generative Adversarial Network) using PyTorch. GAN is a tool for training good generative models and is used in various fields such as image generation, style transfer, and data augmentation. The course will start with the basic concepts of GAN, implement each &hellip; \ub354 \ubcf4\uae30 &quot;Deep Learning PyTorch Course, GAN Implementation&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/36485\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:48:51+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:53:00+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\/36485\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36485\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Deep Learning PyTorch Course, GAN Implementation\",\"datePublished\":\"2024-11-01T09:48:51+00:00\",\"dateModified\":\"2024-11-01T11:53:00+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36485\/\"},\"wordCount\":479,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"PyTorch Study\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/36485\/\",\"url\":\"https:\/\/atmokpo.com\/w\/36485\/\",\"name\":\"Deep Learning PyTorch Course, GAN Implementation - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:48:51+00:00\",\"dateModified\":\"2024-11-01T11:53:00+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36485\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/36485\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/36485\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Deep Learning PyTorch Course, GAN Implementation\"}]},{\"@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":"Deep Learning PyTorch Course, GAN Implementation - \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\/36485\/","og_locale":"ko_KR","og_type":"article","og_title":"Deep Learning PyTorch Course, GAN Implementation - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"In this course, we will provide an in-depth explanation of how to implement GAN (Generative Adversarial Network) using PyTorch. GAN is a tool for training good generative models and is used in various fields such as image generation, style transfer, and data augmentation. The course will start with the basic concepts of GAN, implement each &hellip; \ub354 \ubcf4\uae30 \"Deep Learning PyTorch Course, GAN Implementation\"","og_url":"https:\/\/atmokpo.com\/w\/36485\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:48:51+00:00","article_modified_time":"2024-11-01T11:53:00+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\/36485\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/36485\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Deep Learning PyTorch Course, GAN Implementation","datePublished":"2024-11-01T09:48:51+00:00","dateModified":"2024-11-01T11:53:00+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/36485\/"},"wordCount":479,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["PyTorch Study"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/36485\/","url":"https:\/\/atmokpo.com\/w\/36485\/","name":"Deep Learning PyTorch Course, GAN Implementation - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:48:51+00:00","dateModified":"2024-11-01T11:53:00+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/36485\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/36485\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/36485\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Deep Learning PyTorch Course, GAN Implementation"}]},{"@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\/36485","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=36485"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36485\/revisions"}],"predecessor-version":[{"id":36486,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36485\/revisions\/36486"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=36485"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=36485"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=36485"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}