1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
| import torch import torch.nn as nn from torch.optim import Adam import torch.utils.data as Data import torchvision from torchvision import transforms import numpy as np
'''定义生成器''' class Generator(nn.Module): def __init__(self, input_shape, output_shape): super().__init__()
self.input_shape = input_shape self.output_shape = output_shape
self.layer1 = nn.Sequential( nn.Linear(self.input_shape, 256), nn.BatchNorm1d(256, momentum=0.8), nn.ReLU(), )
self.layer2 = nn.Sequential( nn.Linear(256, 512), nn.BatchNorm1d(512, momentum=0.8), nn.ReLU(), )
self.layer3 = nn.Sequential( nn.Linear(512, 1024), nn.BatchNorm1d(1024, momentum=0.8), nn.ReLU(), )
self.layer4 = nn.Sequential( nn.Linear(1024, int(np.prod(self.output_shape))), nn.Sigmoid() )
def forward(self, tensor_input): x = self.layer1(tensor_input) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) output = x.reshape(-1, *self.output_shape)
return output
'''定义判别器''' class Discriminator(nn.Module): def __init__(self, input_shape): super().__init__()
self.input_shape = input_shape
self.model = nn.Sequential( nn.Flatten(),
nn.Linear(int(np.prod(self.input_shape)), 512), nn.LeakyReLU(negative_slope=0.2),
nn.Linear(512, 256), nn.LeakyReLU(negative_slope=0.2),
nn.Linear(256, 64), nn.LeakyReLU(negative_slope=0.2),
nn.Linear(64, 1), nn.Sigmoid(), )
def forward(self, img): output = self.model(img)
return output
class GAN(): def __init__(self): self.cuda_on = torch.cuda.is_available()
self.input_shape = 100 self.img_shape = (1, 28, 28)
self.generator = Generator(self.input_shape, self.img_shape) self.discriminator = Discriminator(self.img_shape)
self.optim_G = Adam(self.generator.parameters(), lr=2e-4) self.optim_D = Adam(self.discriminator.parameters(), lr=2e-4) self.loss_adver = nn.BCELoss()
if self.cuda_on: self.generator.cuda() self.discriminator.cuda() self.loss_adver.cuda()
def getDataloader(self, batch_size): mnist = torchvision.datasets.MNIST( root='./data/', train=True, transform=transforms.Compose([ transforms.ToTensor(), ]) ) loader = Data.DataLoader(dataset=mnist, batch_size=batch_size, shuffle=True) return loader
def train(self, epochs=1, batch_size=32): loader = self.getDataloader(batch_size)
for epoch in range(epochs): for step, (img_real, _) in enumerate(loader): num = img_real.shape[0]
valid = torch.ones((num, 1), dtype=torch.float32) fake = torch.zeros((num, 1), dtype=torch.float32)
z = torch.randn(num, self.input_shape)
if self.cuda_on: valid = valid.cuda() fake = fake.cuda() z = z.cuda() img_real = img_real.cuda()
img_gen = self.generator(z)
'''训练判别器D''' D_loss_real = self.loss_adver(self.discriminator(img_real), valid) D_loss_fake = self.loss_adver(self.discriminator(img_gen), fake) D_loss = (D_loss_real + D_loss_fake) / 2
self.optim_D.zero_grad() D_loss.backward(retain_graph=True) self.optim_D.step()
'''训练生成器G''' G_loss = self.loss_adver(self.discriminator(img_gen), valid)
self.optim_G.zero_grad() G_loss.backward() self.optim_G.step()
print('Epoch:', epoch+1, ' Step:', step, ' D_loss:', D_loss.item(), ' G_loss:', G_loss.item())
if (step+1) % 400 == 0: torchvision.utils.save_image( img_gen.data[:9], 'gen\\{}_{}.png'.format(epoch, step), nrow=3)
if __name__ == '__main__': gan = GAN() gan.train(epochs=12, batch_size=64)
|