CGAN minist上的简单实现

本文介绍了使用PyTorch 0.4简单实现CGAN的过程,解决了原始GAN模型样本多样性和质量的问题。经过调整,CGAN在第8个epoch时生成的样本既丰富又高质量。提供了训练和主程序的代码片段,尽管代码有些混乱,但能运行并展示CGAN的强大效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CGAN的超简单实现,基于pytorch 0.4。

刚开始搭建了一个原始GAN网络,没多久就遇到模型崩溃的问题,生成的样本丰富性很少,所以索性直接改成CGAN ,整个原理还是很简单的,改起来很快,主要是参数调整真的让人头大。

GAN 训练了35个epoch的效果,几乎只生成3和5的样本。

#CGAN训练效果,第8个epoch , 可以看到生成样本丰富性很高,而且质量很不错。
在这里插入图片描述

代码
代码有点点乱,将就能用就行~
#CGANnets

import torch
import  torch.nn as nn
import torch.functional as F


#变成CGAN 在fc层嵌入 one-ho编码

class discriminator(nn.Module):
    def __init__(self):
        super(discriminator,self).__init__()

        self.conv1 = nn.Sequential(
            nn.Conv2d(1,32,5),
            nn.LeakyReLU(0.2,True),
            nn.MaxPool2d(2,stride = 2),
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(32, 64, 5,padding=2),
            nn.LeakyReLU(0.2, True),
            nn.MaxPool2d(2, stride=2),
        )

        self.fc = nn.Sequential(
            nn.Linear(64*6*6+10,1024),
            nn.LeakyReLU(0.2,True),
            nn.Linear(1024,1),
            nn.Sigmoid()
        )

    def forward(self, x,labels):
        x = self.conv1(x)
        x = self.conv2(x)
        x = x.view(x.size(0),-1)
        x = torch.cat((x,labels),1)

        x = self.fc(x)
        return x

class generator(nn.Module):
    def __init__(self, input_size, num_feature):
        super(generator, self).__init__()
        self.fc = nn.Linear(input_size+10, num_feature)  # batch, 3136=1x56x56
        self.br = nn.Sequential(
            nn.BatchNorm2d(1),
            nn.ReLU(True)
        )

        self.downsample1 = nn.Sequential(
            nn.Conv2d(1,50,3,stride=1,padding=1),
            nn.BatchNorm2d(50),
            nn.ReLU(True)
        )

        self.downsample2 =  nn.Sequential(
            nn.Conv2d(50,25,3,stride=1,padding=1),
            nn.BatchNorm2d(25),
            nn.ReLU(True)
        )

        self.downsample3 = nn.Sequential(
            nn.Conv2d(25,1,2,stride = 2),
            nn.Tanh()
        )

    def forward(self,z,labels):
        '''

        :param x: (batchsize,100)的随机噪声
        :param label:  (batchsize,10) 的one-hot 标签编码
        :return:
        '''
        x = torch.cat((z,labels),1) #沿1维拼接
        x = self.fc(x)

        x = x.view(x.size(0),1,56,56)
        x = self.br(x)
        x = self.downsample1(x)
        x = self.downsample2(x)
        x = self.downsample3(x)

        return  x

##train.py

import torc
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值