当前位置:   article > 正文

PyTorch实现VAE_pytorch编写vae

pytorch编写vae

转载自:https://shenxiaohai.me/2018/10/20/pytorch-tutorial-advanced-02/,本文只做个人记录学习使用,版权归原作者所有。

  1. # 包
  2. import os
  3. import torch
  4. import torch.nn as nn
  5. import torch.nn.functional as F
  6. import torchvision
  7. from torchvision import transforms
  8. from torchvision.utils import save_image
  1. # 设备配置
  2. torch.cuda.set_device(1) # 这句用来设置pytorch在哪块GPU上运行
  3. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  1. # 如果没有文件夹就创建一个文件夹
  2. sample_dir = 'samples'
  3. if not os.path.exists(sample_dir):
  4. os.makedirs(sample_dir)
  1. # 超参数设置
  2. # Hyper-parameters
  3. image_size = 784
  4. h_dim = 400
  5. z_dim = 20
  6. num_epochs = 15
  7. batch_size = 128
  8. learning_rate = 1e-3
  1. dataset = torchvision.datasets.MNIST(root='../../../data/minist',
  2. train=True,
  3. transform=transforms.ToTensor(),
  4. download=True)
  5. # 数据加载器
  6. data_loader = torch.utils.data.DataLoader(dataset=dataset,
  7. batch_size=batch_size,
  8. shuffle=True)
  1. # VAE model
  2. class VAE(nn.Module):
  3. def __init__(self, image_size=784, h_dim=400, z_dim=20):
  4. super(VAE, self).__init__()
  5. self.fc1 = nn.Linear(image_size, h_dim)
  6. self.fc2 = nn.Linear(h_dim, z_dim) # 均值 向量
  7. self.fc3 = nn.Linear(h_dim, z_dim) # 保准方差 向量
  8. self.fc4 = nn.Linear(z_dim, h_dim)
  9. self.fc5 = nn.Linear(h_dim, image_size)
  10. # 编码过程
  11. def encode(self, x):
  12. h = F.relu(self.fc1(x))
  13. return self.fc2(h), self.fc3(h)
  14. # 随机生成隐含向量
  15. def reparameterize(self, mu, log_var):
  16. std = torch.exp(log_var/2)
  17. eps = torch.randn_like(std)
  18. return mu + eps * std
  19. # 解码过程
  20. def decode(self, z):
  21. h = F.relu(self.fc4(z))
  22. return F.sigmoid(self.fc5(h))
  23. # 整个前向传播过程:编码-》解码
  24. def forward(self, x):
  25. mu, log_var = self.encode(x)
  26. z = self.reparameterize(mu, log_var)
  27. x_reconst = self.decode(z)
  28. return x_reconst, mu, log_var
  1. # 实例化一个模型
  2. model = VAE().to(device)
  1. # 创建优化器
  2. optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
  1. for epoch in range(num_epochs):
  2. for i, (x, _) in enumerate(data_loader):
  3. # 获取样本,并前向传播
  4. x = x.to(device).view(-1, image_size)
  5. x_reconst, mu, log_var = model(x)
  6. # 计算重构损失和KL散度(KL散度用于衡量两种分布的相似程度)
  7. # KL散度的计算可以参考论文或者文章开头的链接
  8. reconst_loss = F.binary_cross_entropy(x_reconst, x, size_average=False)
  9. kl_div = - 0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp())
  10. # 反向传播和优化
  11. loss = reconst_loss + kl_div
  12. optimizer.zero_grad()
  13. loss.backward()
  14. optimizer.step()
  15. if (i+1) % 100 == 0:
  16. print ("Epoch[{}/{}], Step [{}/{}], Reconst Loss: {:.4f}, KL Div: {:.4f}"
  17. .format(epoch+1, num_epochs, i+1, len(data_loader), reconst_loss.item(), kl_div.item()))
  18. # 利用训练的模型进行测试
  19. with torch.no_grad():
  20. # 随机生成的图像
  21. z = torch.randn(batch_size, z_dim).to(device)
  22. out = model.decode(z).view(-1, 1, 28, 28)
  23. save_image(out, os.path.join(sample_dir, 'sampled-{}.png'.format(epoch+1)))
  24. # 重构的图像
  25. out, _, _ = model(x)
  26. x_concat = torch.cat([x.view(-1, 1, 28, 28), out.view(-1, 1, 28, 28)], dim=3)
  27. save_image(x_concat, os.path.join(sample_dir, 'reconst-{}.png'.format(epoch+1)))
  1. #导入包
  2. import matplotlib.pyplot as plt # plt 用于显示图片
  3. import matplotlib.image as mpimg # mpimg 用于读取图片
  4. import numpy as np
  1. reconsPath = './samples/reconst-55.png'
  2. Image = mpimg.imread(reconsPath)
  3. plt.imshow(Image) # 显示图片
  4. plt.axis('off') # 不显示坐标轴
  5. plt.show()

 

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

闽ICP备14008679号