import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import transforms
from torchvision.utils import save_image
# 配置GPU或CPU設置
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# 創建目錄
# Create a directory if not exists
sample_dir = 'samples'
if not os.path.exists(sample_dir):
os.makedirs(sample_dir)
# 超參數設置
# Hyper-parameters
image_size = 784
h_dim = 400
z_dim = 20
num_epochs = 15
batch_size = 128
learning_rate = 1e-3
# 獲取數據集
# MNIST dataset
dataset = torchvision.datasets.MNIST(root='./data',
train=True,
transform=transforms.ToTensor(),
download=True)
# 數據加載,按照batch_size大小加載,並隨機打亂
data_loader = torch.utils.data.DataLoader(dataset=dataset,
batch_size=batch_size,
shuffle=True)
# 定義VAE類
# VAE model
class VAE(nn.Module):
def __init__(self, image_size=784, h_dim=400, z_dim=20):
super(VAE, self).__init__()
self.fc1 = nn.Linear(image_size, h_dim)
self.fc2 = nn.Linear(h_dim, z_dim)
self.fc3 = nn.Linear(h_dim, z_dim)
self.fc4 = nn.Linear(z_dim, h_dim)
self.fc5 = nn.Linear(h_dim, image_size)
# 編碼 學習高斯分布均值與方差
def encode(self, x):
h = F.relu(self.fc1(x))
return self.fc2(h), self.fc3(h)
# 將高斯分布均值與方差參數重表示,生成隱變量z 若x~N(mu, var*var)分布,則(x-mu)/var=z~N(0, 1)分布
def reparameterize(self, mu, log_var):
std = torch.exp(log_var / 2)
eps = torch.randn_like(std)
return mu + eps * std
# 解碼隱變量z
def decode(self, z):
h = F.relu(self.fc4(z))
return F.sigmoid(self.fc5(h))
# 計算重構值和隱變量z的分布參數
def forward(self, x):
mu, log_var = self.encode(x)# 從原始樣本x中學習隱變量z的分布,即學習服從高斯分布均值與方差
z = self.reparameterize(mu, log_var)# 將高斯分布均值與方差參數重表示,生成隱變量z
x_reconst = self.decode(z)# 解碼隱變量z,生成重構x’
return x_reconst, mu, log_var# 返回重構值和隱變量的分布參數
# 構造VAE實例對象
model = VAE().to(device)
print(model)
# VAE( (fc1): Linear(in_features=784, out_features=400, bias=True)
# (fc2): Linear(in_features=400, out_features=20, bias=True)
# (fc3): Linear(in_features=400, out_features=20, bias=True)
# (fc4): Linear(in_features=20, out_features=400, bias=True)
# (fc5): Linear(in_features=400, out_features=784, bias=True))
# 選擇優化器,並傳入VAE模型參數和學習率
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
#開始訓練
for epoch in range(num_epochs):
for i, (x, _) in enumerate(data_loader):
# 前向傳播
x = x.to(device).view(-1, image_size)# 將batch_size*1*28*28 ---->batch_size*image_size 其中,image_size=1*28*28=784
x_reconst, mu, log_var = model(x)# 將batch_size*748的x輸入模型進行前向傳播計算,重構值和服從高斯分布的隱變量z的分布參數(均值和方差)
# 計算重構損失和KL散度
# Compute reconstruction loss and kl divergence
# For KL divergence, see Appendix B in VAE paper or http://yunjey47.tistory.com/43
# 重構損失
reconst_loss = F.binary_cross_entropy(x_reconst, x, size_average=False)
# KL散度
kl_div = - 0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp())
# 反向傳播與優化
# 計算誤差(重構誤差和KL散度值)
loss = reconst_loss + kl_div
# 清空上一步的殘余更新參數值
optimizer.zero_grad()
# 誤差反向傳播, 計算參數更新值
loss.backward()
# 將參數更新值施加到VAE model的parameters上
optimizer.step()
# 每迭代一定步驟,打印結果值
if (i + 1) % 10 == 0:
print ("Epoch[{}/{}], Step [{}/{}], Reconst Loss: {:.4f}, KL Div: {:.4f}"
.format(epoch + 1, num_epochs, i + 1, len(data_loader), reconst_loss.item(), kl_div.item()))
with torch.no_grad():
# Save the sampled images
# 保存采樣值
# 生成隨機數 z
z = torch.randn(batch_size, z_dim).to(device)# z的大小為batch_size * z_dim = 128*20
# 對隨機數 z 進行解碼decode輸出
out = model.decode(z).view(-1, 1, 28, 28)
# 保存結果值
save_image(out, os.path.join(sample_dir, 'sampled-{}.png'.format(epoch + 1)))
# Save the reconstructed images
# 保存重構值
# 將batch_size*748的x輸入模型進行前向傳播計算,獲取重構值out
out, _, _ = model(x)
# 將輸入與輸出拼接在一起輸出保存 batch_size*1*28*(28+28)=batch_size*1*28*56
x_concat = torch.cat([x.view(-1, 1, 28, 28), out.view(-1, 1, 28, 28)], dim=3)
save_image(x_concat, os.path.join(sample_dir, 'reconst-{}.png'.format(epoch + 1)))
大概長這么個樣子:

附上一張結果圖:

