雖然GAN現(xiàn)在已經(jīng)有了很多更新和分支笛园,但是要接觸這一行懦胞,鼻祖的文章還是要做一下的。下面是pytorch版的GAN代碼解讀脊串,主要是對(duì)代碼進(jìn)行解釋?zhuān)瑤椭鯇W(xué)者更好的了解GAN辫呻。
訓(xùn)練集
GAN用的訓(xùn)練集為MNIST訓(xùn)練集,這個(gè)在pytorch中已經(jīng)集成了琼锋,可以很方便的下載和調(diào)用放闺。
# Configure data loader
os.makedirs("../../data/mnist", exist_ok=True)#創(chuàng)建文件夾
dataloader = torch.utils.data.DataLoader(
datasets.MNIST(
"../../data/mnist",
train=True,
download=True,
transform=transforms.Compose(
[transforms.Resize(opt.img_size), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]
),
),
batch_size=opt.batch_size,
shuffle=True,
)
使用torchvision.transforms進(jìn)行圖像增強(qiáng),compose()將多個(gè)transform組合起來(lái)使用斩例。ToTensor()把圖像或者是數(shù)組轉(zhuǎn)化為形狀為 [C,H,W] 雄人,取值范圍是 [0,1.0] 的 torch.FloadTensor。Normalize(mean,std)歸一化操作念赶,給定均值和方差將把Tensor正則化础钠。
torch.utils.data.DataLoader()具體解釋請(qǐng)進(jìn)這個(gè)鏈接
現(xiàn)在數(shù)據(jù)集已經(jīng)讀取進(jìn)來(lái)了,下面進(jìn)行構(gòu)建模塊叉谜。
Generator模塊搭建
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
def block(in_feat, out_feat, normalize=True):
layers = [nn.Linear(in_feat, out_feat)]
if normalize:
layers.append(nn.BatchNorm1d(out_feat, 0.8))
layers.append(nn.LeakyReLU(0.2, inplace=True))
return layers
self.model = nn.Sequential(
*block(opt.latent_dim, 128, normalize=False),
*block(128, 256),
*block(256, 512),
*block(512, 1024),
nn.Linear(1024, int(np.prod(img_shape))),
nn.Tanh()
)
def forward(self, z):
img = self.model(z)
img = img.view(img.size(0), *img_shape)
return img
這兒提一下super用法旗吁,super首先找到Generator的父類(lèi),然后把類(lèi)Generator的對(duì)象轉(zhuǎn)化為他的父類(lèi)的對(duì)象停局。
然后block是接收一個(gè)元祖很钓,block是接收一個(gè)字典。
nn.linear():維度轉(zhuǎn)換
nn.BatchNorm1d():對(duì)輸入進(jìn)行批標(biāo)準(zhǔn)化處理
nn.LeakyReLU(negative_slope,inplace):
數(shù)學(xué)表達(dá)式:LeakyReLU(x) = max(0,x)+negative_slopemin(0,x)
inplace=True:將得到的值覆蓋之前的值董栽。
nn.Sequential():時(shí)序容器码倦,modules會(huì)以他們傳入的順序被添加到容器中。
.view()函數(shù):重構(gòu)張量的維度锭碳。
總結(jié):這兒是將z值傳入袁稽,然后加幾個(gè)全連接層,然后輸出擒抛!
Discriminator模塊搭建
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.model = nn.Sequential(
nn.Linear(int(np.prod(img_shape)), 512),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(512, 256),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(256, 1),
nn.Sigmoid(),
)
def forward(self, img):
img_flat = img.view(img.size(0), -1)
validity = self.model(img_flat)
return validity
這兒跟上面生成器都是做幾個(gè)全連接層推汽。
訓(xùn)練準(zhǔn)備
os.makedirs("images", exist_ok=True)
parser = argparse.ArgumentParser()
parser.add_argument("--n_epochs", type=int, default=200, help="number of epochs of training")
parser.add_argument("--batch_size", type=int, default=64, help="size of the batches")
parser.add_argument("--lr", type=float, default=0.0002, help="adam: learning rate")
parser.add_argument("--b1", type=float, default=0.5, help="adam: decay of first order momentum of gradient")
parser.add_argument("--b2", type=float, default=0.999, help="adam: decay of first order momentum of gradient")
parser.add_argument("--n_cpu", type=int, default=8, help="number of cpu threads to use during batch generation")
parser.add_argument("--latent_dim", type=int, default=100, help="dimensionality of the latent space")
parser.add_argument("--img_size", type=int, default=28, help="size of each image dimension")
parser.add_argument("--channels", type=int, default=1, help="number of image channels")
parser.add_argument("--sample_interval", type=int, default=400, help="interval betwen image samples")
opt = parser.parse_args()
print(opt)
img_shape = (opt.channels, opt.img_size, opt.img_size)
cuda = True if torch.cuda.is_available() else False
# Loss function
adversarial_loss = torch.nn.BCELoss()
# Initialize generator and discriminator
generator = Generator()
discriminator = Discriminator()
# Optimizers
optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))
optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))
Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor
if cuda:
generator.cuda()
discriminator.cuda()
adversarial_loss.cuda()
- argparse,這個(gè)模塊在這兒有介紹,
然后在img_shape中調(diào)用argparse模塊的參數(shù)歧沪。 - cuda這句話(huà)是判斷cuda是否能用歹撒,返回值為布爾值。
- loss函數(shù)诊胞,torch.nn.BCELoss()是一個(gè)二分類(lèi)交叉熵暖夭,定義如下:
用N表示樣本數(shù)量,表示預(yù)測(cè)第n個(gè)樣本為正例的概率,表示第n個(gè)樣本的標(biāo)簽鳞尔,則:
這不就是論文中定義的公式么嬉橙! - optimzer:這兒統(tǒng)一使用Adam優(yōu)化器早直,不再贅述寥假。
- Tensor:轉(zhuǎn)換為GPU的張量類(lèi)型。
開(kāi)始訓(xùn)練
# ----------
# Training
# ----------
for epoch in range(opt.n_epochs):
for i, (imgs, _) in enumerate(dataloader):
# Adversarial ground truths
valid = Variable(Tensor(imgs.size(0), 1).fill_(1.0), requires_grad=False)
fake = Variable(Tensor(imgs.size(0), 1).fill_(0.0), requires_grad=False)
# Configure input
real_imgs = Variable(imgs.type(Tensor))
# -----------------
# Train Generator
# -----------------
optimizer_G.zero_grad()
# Sample noise as generator input
z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], opt.latent_dim))))
# Generate a batch of images
gen_imgs = generator(z)
# Loss measures generator's ability to fool the discriminator
g_loss = adversarial_loss(discriminator(gen_imgs), valid)
g_loss.backward()
optimizer_G.step()
# ---------------------
# Train Discriminator
# ---------------------
optimizer_D.zero_grad()
# Measure discriminator's ability to classify real from generated samples
real_loss = adversarial_loss(discriminator(real_imgs), valid)
fake_loss = adversarial_loss(discriminator(gen_imgs.detach()), fake)
d_loss = (real_loss + fake_loss) / 2
d_loss.backward()
optimizer_D.step()
print(
"[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]"
% (epoch, opt.n_epochs, i, len(dataloader), d_loss.item(), g_loss.item())
)
batches_done = epoch * len(dataloader) + i
if batches_done % opt.sample_interval == 0:
save_image(gen_imgs.data[:25], "images/%d.png" % batches_done, nrow=5, normalize=True)
- 首先兩個(gè)循環(huán)霞扬,對(duì)應(yīng)論文中兩個(gè)for循環(huán)糕韧,只不過(guò)這兒D和G是一對(duì)一關(guān)系。
- Variable:對(duì)Tensor進(jìn)行封裝喻圃,然后整合了反向傳播萤彩,用變量.backward()進(jìn)行反向傳播之后,var.grad中保存了var的梯度斧拍。
Variable包含了三個(gè)屬性:
- data:儲(chǔ)存了Tensor雀扶,是本體的數(shù)據(jù)
- grad:保存了data的梯度,本身是個(gè)Variable而非Tensor肆汹,與data形狀一致
- grad_fn:指向Function對(duì)象愚墓,用于反向傳播的梯度計(jì)算使用
- .zero_grad():將模型的參數(shù)梯度設(shè)置為0
- z:初始化噪聲
- g_loss:先前向再后向。
- step():模型更新
下面的D跟上述的G是類(lèi)似的思路昂勉。最下面就是輸出一些信息浪册。