当前位置:   article > 正文

Variational Auto-encoder(VAE)变分自编码器-Pytorch

variational autoencoders pytorch
 
  
  1. import os
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. import torchvision
  6. from torchvision import transforms
  7. from torchvision.utils import save_image
  8. # 配置GPU或CPU设置
  9. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  10. # 创建目录
  11. # Create a directory if not exists
  12. sample_dir = 'samples'
  13. if not os.path.exists(sample_dir):
  14. os.makedirs(sample_dir)
  15. # 超参数设置
  16. # Hyper-parameters
  17. image_size = 784
  18. h_dim = 400
  19. z_dim = 20
  20. num_epochs = 15
  21. batch_size = 128
  22. learning_rate = 1e-3
  23. # 获取数据集
  24. # MNIST dataset
  25. dataset = torchvision.datasets.MNIST(root='./data',
  26. train=True,
  27. transform=transforms.ToTensor(),
  28. download=True)
  29. # 数据加载,按照batch_size大小加载,并随机打乱
  30. data_loader = torch.utils.data.DataLoader(dataset=dataset,
  31. batch_size=batch_size,
  32. shuffle=True)
  33. # 定义VAE类
  34. # VAE model
  35. class VAE(nn.Module):
  36. def __init__(self, image_size=784, h_dim=400, z_dim=20):
  37. super(VAE, self).__init__()
  38. self.fc1 = nn.Linear(image_size, h_dim)
  39. self.fc2 = nn.Linear(h_dim, z_dim)
  40. self.fc3 = nn.Linear(h_dim, z_dim)
  41. self.fc4 = nn.Linear(z_dim, h_dim)
  42. self.fc5 = nn.Linear(h_dim, image_size)
  43. # 编码 学习高斯分布均值与方差
  44. def encode(self, x):
  45. h = F.relu(self.fc1(x))
  46. return self.fc2(h), self.fc3(h)
  47. # 将高斯分布均值与方差参数重表示,生成隐变量z 若x~N(mu, var*var)分布,则(x-mu)/var=z~N(0, 1)分布
  48. def reparameterize(self, mu, log_var):
  49. std = torch.exp(log_var / 2)
  50. eps = torch.randn_like(std)
  51. return mu + eps * std
  52. # 解码隐变量z
  53. def decode(self, z):
  54. h = F.relu(self.fc4(z))
  55. return F.sigmoid(self.fc5(h))
  56. # 计算重构值和隐变量z的分布参数
  57. def forward(self, x):
  58. mu, log_var = self.encode(x)# 从原始样本x中学习隐变量z的分布,即学习服从高斯分布均值与方差
  59. z = self.reparameterize(mu, log_var)# 将高斯分布均值与方差参数重表示,生成隐变量z
  60. x_reconst = self.decode(z)# 解码隐变量z,生成重构x’
  61. return x_reconst, mu, log_var# 返回重构值和隐变量的分布参数
  62. # 构造VAE实例对象
  63. model = VAE().to(device)
  64. print(model)
  65. # VAE( (fc1): Linear(in_features=784, out_features=400, bias=True)
  66. # (fc2): Linear(in_features=400, out_features=20, bias=True)
  67. # (fc3): Linear(in_features=400, out_features=20, bias=True)
  68. # (fc4): Linear(in_features=20, out_features=400, bias=True)
  69. # (fc5): Linear(in_features=400, out_features=784, bias=True))
  70. # 选择优化器,并传入VAE模型参数和学习率
  71. optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
  72. #开始训练
  73. for epoch in range(num_epochs):
  74. for i, (x, _) in enumerate(data_loader):
  75. # 前向传播
  76. x = x.to(device).view(-1, image_size)# 将batch_size*1*28*28 ---->batch_size*image_size 其中,image_size=1*28*28=784
  77. x_reconst, mu, log_var = model(x)# 将batch_size*748的x输入模型进行前向传播计算,重构值和服从高斯分布的隐变量z的分布参数(均值和方差)
  78. # 计算重构损失和KL散度
  79. # Compute reconstruction loss and kl divergence
  80. # For KL divergence, see Appendix B in VAE paper or http://yunjey47.tistory.com/43
  81. # 重构损失
  82. reconst_loss = F.binary_cross_entropy(x_reconst, x, size_average=False)
  83. # KL散度
  84. kl_div = - 0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp())
  85. # 反向传播与优化
  86. # 计算误差(重构误差和KL散度值)
  87. loss = reconst_loss + kl_div
  88. # 清空上一步的残余更新参数值
  89. optimizer.zero_grad()
  90. # 误差反向传播, 计算参数更新值
  91. loss.backward()
  92. # 将参数更新值施加到VAE model的parameters上
  93. optimizer.step()
  94. # 每迭代一定步骤,打印结果值
  95. if (i + 1) % 10 == 0:
  96. print ("Epoch[{}/{}], Step [{}/{}], Reconst Loss: {:.4f}, KL Div: {:.4f}"
  97. .format(epoch + 1, num_epochs, i + 1, len(data_loader), reconst_loss.item(), kl_div.item()))
  98. with torch.no_grad():
  99. # Save the sampled images
  100. # 保存采样值
  101. # 生成随机数 z
  102. z = torch.randn(batch_size, z_dim).to(device)# z的大小为batch_size * z_dim = 128*20
  103. # 对随机数 z 进行解码decode输出
  104. out = model.decode(z).view(-1, 1, 28, 28)
  105. # 保存结果值
  106. save_image(out, os.path.join(sample_dir, 'sampled-{}.png'.format(epoch + 1)))
  107. # Save the reconstructed images
  108. # 保存重构值
  109. # 将batch_size*748的x输入模型进行前向传播计算,获取重构值out
  110. out, _, _ = model(x)
  111. # 将输入与输出拼接在一起输出保存 batch_size*1*28*(28+28)=batch_size*1*28*56
  112. x_concat = torch.cat([x.view(-1, 1, 28, 28), out.view(-1, 1, 28, 28)], dim=3)
  113. save_image(x_concat, os.path.join(sample_dir, 'reconst-{}.png'.format(epoch + 1)))
 
 

 大概长这么个样子:

附上一张结果图:

转载于:https://www.cnblogs.com/jeshy/p/11437547.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/72983
推荐阅读
相关标签
  

闽ICP备14008679号