[pytorch]GAN网络实现----MNIST

it2023-06-10  73

对判别网络的参数进行了固定修改。

import torch import torchvision from torchvision import transforms from torchvision.utils import save_image from torch import nn from torch.autograd import Variable from torch import optim import os transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)), ]) mnist = torchvision.datasets.MNIST(root='./data', train=True, download=False, transform=transform) dataloader = torch.utils.data.DataLoader(mnist, batch_size=100, shuffle=True) class Dnet(nn.Module): def __init__(self): super(Dnet, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d(1, 6, 3, padding=2), # batch, 6, 30,30 nn.LeakyReLU(0.2, True), nn.MaxPool2d(2, stride=2), # batch, 6, 15, 15 ) self.conv2 = nn.Sequential( nn.Conv2d(6, 12, 3, padding=2), # batch, 12, 17, 17 nn.LeakyReLU(0.2, True), nn.MaxPool2d(2, stride=2) # batch, 12, 8, 8 ) self.fc = nn.Sequential( nn.Linear(12 * 8 * 8, 1024), nn.LeakyReLU(0.2, True), nn.Linear(1024, 1), nn.Sigmoid() ) def forward(self, x): ''' x: batch, width, height, channel=1 ''' x = self.conv1(x) x = self.conv2(x) x = x.view(x.size(0), -1) # 将第二次卷积的输出拉伸为一行 x = self.fc(x) return x class Gnet(nn.Module): def __init__(self): super(Gnet, self).__init__() self.fc = nn.Linear(128, 784) # batch, 1,28,28 self.br = nn.Sequential( nn.BatchNorm2d(1), nn.ReLU(True) ) self.downsample1 = nn.Sequential( nn.Conv2d(1, 12, 3, stride=1, padding=1), # batch, 12, 28, 28 nn.BatchNorm2d(12), nn.ReLU(True) ) self.downsample2 = nn.Sequential( nn.Conv2d(12, 6, 3, stride=1, padding=1), # batch, 6, 28, 28 nn.BatchNorm2d(6), nn.ReLU(True) ) self.downsample3 = nn.Sequential( nn.Conv2d(6, 1, 3, stride=1, padding=1), # batch, 1, 28, 28 nn.Tanh() ) def forward(self, x): x = self.fc(x) x = x.view(x.size(0), 1, 28, 28) x = self.br(x) x = self.downsample1(x) x = self.downsample2(x) x = self.downsample3(x) return x def to_img(x): y = (x + 1) * 0.5 y = y.clamp(0, 1) y = y.view(-1, 1, 28, 28) return y class Net: def __init__(self): self.dnet = Dnet() self.gnet = Gnet() self.dnet = self.dnet.cuda() self.gnet = self.gnet.cuda() self.Loss = nn.BCELoss() self.d_optimizer = optim.Adam(self.dnet.parameters(), lr=0.0002) self.g_optimizer = optim.Adam(self.gnet.parameters(), lr=0.0002) def forward(self, real_x, fack_x): self.real_d_out = self.dnet(real_x) g_out = self.gnet(fack_x) self.g_d_out = net.dnet(g_out.detach()) def backward(self, pos_y, nega_y, fack_xs): d_out_loss = self.Loss(self.real_d_out, pos_y) g_d_loss = self.Loss(self.g_d_out, nega_y) self.d_loss = d_out_loss + g_d_loss self.d_optimizer.zero_grad() self.d_loss.backward(retain_graph = True) self.d_optimizer.step() self.fack_g_out = self.gnet(fack_xs) self.fack_g_d_out = self.dnet(self.fack_g_out) self.g_loss = self.Loss(self.fack_g_d_out, pos_y) self.g_optimizer.zero_grad() self.g_loss.backward() self.g_optimizer.step() if __name__ == '__main__': if not os.path.exists('img'): os.mkdir('img') net = Net() for i in range(100): for x, y in dataloader: # x = x.view(x.size(0),-1) real_x = Variable(x).cuda() fack_x = Variable(torch.randn(100, 128)).cuda() pos_y = Variable(torch.ones(100)).cuda() nega_y = Variable(torch.zeros(100)).cuda() fack_xs = Variable(torch.randn(100, 128)).cuda() net.forward(real_x, fack_x) net.backward(pos_y, nega_y, fack_xs) img = to_img(net.fack_g_out.data) D_Accuracy = ((net.real_d_out.mean() + 1 - net.fack_g_d_out.mean()) / 2).item() print(net.d_loss.item(), net.g_loss.item(), D_Accuracy) save_image(img, './img/fake_images-{}.png'.format(i + 1))

代码来源:https://blog.csdn.net/weixin_38241876/article/details/88232720?ops_request_misc

最新回复(0)