<jupyter_start><jupyter_text>定义网络<jupyter_code>#权重初始化
def weights_init(m):
    classname=m.__class__.__name__
    if classname.find('Conv') != -1:
        m.weight.data.normal_(0.0,0.02)
    elif classname.find('BatchNorm') != -1:
        m.weight.data.normal_(1.0,0.02)
        m.bias.data.fill_(0)

#生成网络
class Gen(nn.Module):
    def __init__(self):
        super(Gen,self).__init__()
        self.main=nN.Squential(
            nn.ConvTranspose2d(nz,ngf*8,4,1,0,bias=False),
            nn.BatchNorm2d(ngf*8),
            nn.ReLU(True),
            #输出ngf*8x4x4
            nn.ConvTranspose2d(ngf*8,ngf*4,4,2,1,bias=False),
            nn.BatchNorm2d(ngf*4),
            nn.ReLU(True),
            #输出ngf*4x8x8
            nn.ConvTranspose2d(ngf*4,ngf*2,4,2,1,bias=False),
            nn.BatchNorm2d(ngf*2),
            nn.ReLU(True),
            #输出ngf*2x16x16
            nn.ConvTranspose2d(ngf*2,ngf,4,2,1,bias=False),
            nn.BatchNorm2d(ngf),
            nn.ReLU(True),
            #输出ngfx32x32
            nn.ConvTranspose2d(ngf,nc,4,2,1,bias=False),
            nn.Tanh()
            #输出ncx64x64
        )
        
    def forward(self,input):
            output=self.main(input)
            return output
            
netG=Gen()
netG.apply(weights_init)
print(netG)
#判别网络
class Dis(nn.Module):
    def __init__(self):
        super(Dis,self).__init__()
        self.main=nn.Sequential(
            #输入ncx64x64
            nn.Conv2d(nc,ndf,4,2,1,bias=False),
            nn.LeakyReLU(0.2,inplace=True),
            #输出ndfx32x32
            nn.Conv2d(ndf,ndf*2,4,2,1,bias=False),
            nn.BatchNorm2d(ngf*2),
            nn.LeakyReLU(0.2,inplace=True),
            #输出ndf*2x16x16
            nn.Conv2d(ndf*2,ndf*4,4,2,1,bias=False),
            nn.BatchNorm2d(ngf*4),
            nn.LeakyReLU(0.2,inplace=True),
            #输出ndf*4x8x8
            nn.Conv2d(ndf*4,ndf*8,4,2,1,bias=False),
            nn.BatchNorm2d(ngf*8),
            nn.LeakyReLU(0.2,inplace=True),
            #输出ndf*8x4x4
            nn.Conv2d(ndf*8,1,4,1,0,bias=False),
            nn.Sigmoid()
        )
    def forward(self,input):
        output=self.main(input)
        return output.view(-1,1).squeeze(1)
    
netD=Dis()
netD.apply(weights_init)
print(netD)<jupyter_output><empty_output><jupyter_text>定义损失和优化<jupyter_code>criterion=nn.BCELoss()
optimizerD=optim.Adam(netD.parameters(),lr,betas=(betal,0.999))
optimizerG=optim.Adam(netG.parameters(),lr,betas=(betal,0.999))<jupyter_output><empty_output><jupyter_text>训练网络<jupyter_code>for epoch in range(niter):
    #更新D
    #使用真数据训练
    netD.zero_grad()
    real,_=data  #获取一批真实数据
    batch_size=real.size(0)
    if torch.cuda.is_available():
        real=real.cuda()
        
    input.resize_as_(real).copy_(real)
    label.resize_(batch_size).fill_(real_label)
    inputv=Variable(input)
    labelv=Variable(label)
    
    output=netD(inputv)  
    errD_real=criterion(output,labelv)
    errD_real.backward()
    D_x=output.data.mean()
    
    #使用假数据训练
    noise.resize_(batch_size,nz,1,1).normal_(0,1) #随机生成一批维度为nz的1x1噪声向量
    noisev=Variable(noise)
    
    fake=netG(noisev)
    labelv=Variable(label.fill_(fake_label))
    
    output=netD(fake.detach())
    errD_fake=criterion(output,labelv)
    errD_fake.backward()
    D_G_z1=output.data.mean()
    
    errD=errD_real+errD_fake
    optimizerD.step()
    
    #更新G
    netG.zero_grad()
    labelv=Variable(label.fill_(real_label))
    
    output=netD(fake)
    errG=criterion(output,labelv)
    errG.backward()
    D_G_z2=output.data.mean()
    
    optimizerG.step()
    
    print('[%d/%d][%d/%d] LOSS_D: %.4f LOSS_G: %.4f D(x): %.4f D(G(z)): %.4f/%.4f' % (epoch,niter,i,len(dataloader),
                                                                                      errD.data[0],errG.data[0],D_x,D_G_z1,D_G_z2))
    if i % 100 ==0:
        vutils.save_image(real_cpu,'%s/real_samples.png' % outf,normalize=True)
        fake=netG(fixed_noise)
        vutils.save_image(fake.data,'%s/fake_samples_epoch_%03d.png' % (outf,epoch),normalize=True)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1503539175006102, 'fraction_numerical': 0.03905296558457408, 'mean_word_length': 2.4379194630872485, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '464596', 'license': 'MIT', 'n_tokens_mistral': 1755, 'n_tokens_neox': 1749, 'n_words': 142, 'path': 'gan3.ipynb', 'repo_name': 'Swimmingswam/palmprint', 'size': '4097'}