{"id":36381,"date":"2024-11-01T09:48:01","date_gmt":"2024-11-01T09:48:01","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=36381"},"modified":"2024-11-01T11:00:09","modified_gmt":"2024-11-01T11:00:09","slug":"deep-learning-with-gan-using-pytorch-animalgan","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/36381\/","title":{"rendered":"Deep Learning with GAN Using PyTorch, AnimalGAN"},"content":{"rendered":"<p><body><\/p>\n<h2>1. Introduction<\/h2>\n<p>\n        Generative Adversarial Networks (GANs) are models that learn through the adversarial interplay of two neural networks: a Generator and a Discriminator. This structure has garnered significant attention in various advanced deep learning applications, such as image generation, transformation, and style transfer. In this article, we will explore the basic principles of GANs using PyTorch and delve into AnimalGAN, which generates animal images.\n    <\/p>\n<h2>2. Basic Principles of GANs<\/h2>\n<p>\n        GANs primarily consist of two neural networks. The Generator takes a random noise vector as input and generates fake images, while the Discriminator distinguishes between real images and generated fakes. Both neural networks are optimized by interfering with each other&#8217;s learning process. This process is similar to a &#8216;zero-sum game&#8217; in game theory. The Generator continually improves to evade the Discriminator, which enhances its ability to judge the authenticity of images produced by the Generator.\n    <\/p>\n<h3>2.1 GAN Learning Process<\/h3>\n<p>\n        The learning process proceeds through the following steps:<\/p>\n<ol>\n<li>Train the Discriminator with real data.<\/li>\n<li>Generate random noise and create fake images using the Generator.<\/li>\n<li>Retrain the Discriminator with fake images.<\/li>\n<li>Repeat the above steps.<\/li>\n<\/ol>\n<h2>3. Implementing GAN Using PyTorch<\/h2>\n<p>\n        Now, let&#8217;s implement a simple GAN using PyTorch. The entire process can be divided into preparatory steps, model implementation, training, and visualization of generated images.\n    <\/p>\n<h3>3.1 Environment Setup<\/h3>\n<pre><code>python\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision.transforms as transforms\nfrom torchvision import datasets\nfrom torch.utils.data import DataLoader\nimport matplotlib.pyplot as plt\nimport numpy as np\n    <\/code><\/pre>\n<h3>3.2 Preparing the Dataset<\/h3>\n<p>\n        For the AnimalGAN project, either the CIFAR-10 or an animal image dataset can be used. Here, we will load the CIFAR-10 dataset.\n    <\/p>\n<pre><code>python\ntransform = transforms.Compose([\n    transforms.Resize(64),\n    transforms.ToTensor(),\n    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n])\n\n# Load CIFAR-10 dataset\ndataset = datasets.CIFAR10(root='.\/data', train=True, download=True, transform=transform)\ndataloader = DataLoader(dataset, batch_size=128, shuffle=True)\n    <\/code><\/pre>\n<h3>3.3 Implementing the GAN Model<\/h3>\n<p>\n        The GAN model consists of a Generator and a Discriminator. The Generator accepts a noise vector as input and generates an image, while the Discriminator serves the role of distinguishing whether the image is real or fake.\n    <\/p>\n<pre><code>python\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(True),\n            nn.Linear(256, 512),\n            nn.ReLU(True),\n            nn.Linear(512, 1024),\n            nn.ReLU(True),\n            nn.Linear(1024, 3 * 64 * 64),  # CIFAR-10 image size\n            nn.Tanh()  # Output range [-1, 1]\n        )\n\n    def forward(self, z):\n        return self.model(z).view(-1, 3, 64, 64)\n\nclass Discriminator(nn.Module):\n    def __init__(self):\n        super(Discriminator, self).__init__()\n        self.model = nn.Sequential(\n            nn.Linear(3 * 64 * 64, 512),\n            nn.LeakyReLU(0.2),\n            nn.Linear(512, 256),\n            nn.LeakyReLU(0.2),\n            nn.Linear(256, 1),\n            nn.Sigmoid()  # Output in range [0, 1]\n        )\n\n    def forward(self, img):\n        return self.model(img.view(-1, 3 * 64 * 64))\n    <\/code><\/pre>\n<h3>3.4 Training the Model<\/h3>\n<p>\n        The training process for the GAN alternates between training the Discriminator and the Generator. We will train the GAN using the following code.\n    <\/p>\n<pre><code>python\n# Define the model, loss function, and optimizers\ngenerator = Generator().cuda()\ndiscriminator = Discriminator().cuda()\ncriterion = nn.BCELoss()\noptimizer_G = optim.Adam(generator.parameters(), lr=0.0002, betas=(0.5, 0.999))\noptimizer_D = optim.Adam(discriminator.parameters(), lr=0.0002, betas=(0.5, 0.999))\n\n# Training loop\nnum_epochs = 50\nfor epoch in range(num_epochs):\n    for i, (imgs, _) in enumerate(dataloader):\n        # Set real and fake image labels\n        real_imgs = imgs.cuda()\n        batch_size = real_imgs.size(0)\n        labels_real = torch.ones(batch_size, 1).cuda()\n        labels_fake = torch.zeros(batch_size, 1).cuda()\n\n        # Train Discriminator\n        optimizer_D.zero_grad()\n        outputs_real = discriminator(real_imgs)\n        loss_real = criterion(outputs_real, labels_real)\n\n        z = torch.randn(batch_size, 100).cuda()  # Generate noise\n        fake_imgs = generator(z)\n        outputs_fake = discriminator(fake_imgs.detach())\n        loss_fake = criterion(outputs_fake, labels_fake)\n\n        loss_D = loss_real + loss_fake\n        loss_D.backward()\n        optimizer_D.step()\n\n        # Train Generator\n        optimizer_G.zero_grad()\n        outputs_fake = discriminator(fake_imgs)\n        loss_G = criterion(outputs_fake, labels_real)  # Train to recognize fake images as real\n        loss_G.backward()\n        optimizer_G.step()\n\n    print(f'Epoch [{epoch}\/{num_epochs}], Loss D: {loss_D.item():.4f}, Loss G: {loss_G.item():.4f}')\n    <\/code><\/pre>\n<h3>3.5 Visualization of Results<\/h3>\n<p>\n        After the training is complete, we can visualize the generated images to evaluate the performance of the GAN. The following is code to visualize several generated images.\n    <\/p>\n<pre><code>python\ndef show_generated_images(model, num_images=25):\n    z = torch.randn(num_images, 100).cuda()\n    with torch.no_grad():\n        generated_imgs = model(z)\n    generated_imgs = generated_imgs.cpu().numpy()\n    generated_imgs = (generated_imgs + 1) \/ 2  # Transform to range [0, 1]\n\n    fig, axes = plt.subplots(5, 5, figsize=(10, 10))\n    for i, ax in enumerate(axes.flatten()):\n        ax.imshow(generated_imgs[i].transpose(1, 2, 0))  # Adjust channel order for images\n        ax.axis('off')\n    plt.tight_layout()\n    plt.show()\n\nshow_generated_images(generator)\n    <\/code><\/pre>\n<h2>4. Conclusion<\/h2>\n<p>\n        In this article, we implemented AnimalGAN, which generates animal images using GANs and PyTorch. By understanding the basic principles of GANs and observing results through code, we could clearly grasp the concepts and operations of GANs. GANs remain an active area of research, with more advanced models and techniques continually emerging. Through such various attempts, we can explore more possibilities.\n    <\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. Introduction Generative Adversarial Networks (GANs) are models that learn through the adversarial interplay of two neural networks: a Generator and a Discriminator. This structure has garnered significant attention in various advanced deep learning applications, such as image generation, transformation, and style transfer. In this article, we will explore the basic principles of GANs using &hellip; <a href=\"https:\/\/atmokpo.com\/w\/36381\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Deep Learning with GAN Using PyTorch, AnimalGAN&#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-36381","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>Deep Learning with GAN Using PyTorch, AnimalGAN - \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\/36381\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Deep Learning with GAN Using PyTorch, AnimalGAN - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"1. Introduction Generative Adversarial Networks (GANs) are models that learn through the adversarial interplay of two neural networks: a Generator and a Discriminator. This structure has garnered significant attention in various advanced deep learning applications, such as image generation, transformation, and style transfer. In this article, we will explore the basic principles of GANs using &hellip; \ub354 \ubcf4\uae30 &quot;Deep Learning with GAN Using PyTorch, AnimalGAN&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/36381\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:48:01+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:00:09+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\/36381\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36381\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Deep Learning with GAN Using PyTorch, AnimalGAN\",\"datePublished\":\"2024-11-01T09:48:01+00:00\",\"dateModified\":\"2024-11-01T11:00:09+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36381\/\"},\"wordCount\":402,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"GAN deep learning course\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/36381\/\",\"url\":\"https:\/\/atmokpo.com\/w\/36381\/\",\"name\":\"Deep Learning with GAN Using PyTorch, AnimalGAN - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:48:01+00:00\",\"dateModified\":\"2024-11-01T11:00:09+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36381\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/36381\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/36381\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Deep Learning with GAN Using PyTorch, AnimalGAN\"}]},{\"@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 with GAN Using PyTorch, AnimalGAN - \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\/36381\/","og_locale":"ko_KR","og_type":"article","og_title":"Deep Learning with GAN Using PyTorch, AnimalGAN - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"1. Introduction Generative Adversarial Networks (GANs) are models that learn through the adversarial interplay of two neural networks: a Generator and a Discriminator. This structure has garnered significant attention in various advanced deep learning applications, such as image generation, transformation, and style transfer. In this article, we will explore the basic principles of GANs using &hellip; \ub354 \ubcf4\uae30 \"Deep Learning with GAN Using PyTorch, AnimalGAN\"","og_url":"https:\/\/atmokpo.com\/w\/36381\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:48:01+00:00","article_modified_time":"2024-11-01T11:00:09+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\/36381\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/36381\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Deep Learning with GAN Using PyTorch, AnimalGAN","datePublished":"2024-11-01T09:48:01+00:00","dateModified":"2024-11-01T11:00:09+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/36381\/"},"wordCount":402,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["GAN deep learning course"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/36381\/","url":"https:\/\/atmokpo.com\/w\/36381\/","name":"Deep Learning with GAN Using PyTorch, AnimalGAN - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:48:01+00:00","dateModified":"2024-11-01T11:00:09+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/36381\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/36381\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/36381\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Deep Learning with GAN Using PyTorch, AnimalGAN"}]},{"@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\/36381","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=36381"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36381\/revisions"}],"predecessor-version":[{"id":36382,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36381\/revisions\/36382"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=36381"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=36381"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=36381"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}