一、VAE的具体结构

二、VAE的pytorch实现

1加载并规范化MNIST

import相关类:

from __future__ import print_function
import argparse
import torch
import torch.utils.data
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torchvision import datasets, transforms

设置参数:

parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=128, metavar='N',
help='input batch size for training (default: 128)')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of epochs to train (default: 10)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='enables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
help='how many batches to wait before logging training status')
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()
print(args) #Sets the seed for generating random numbers. And returns a torch._C.Generator object.
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)

输出结果:

Namespace(batch_size=128, cuda=True, epochs=10, log_interval=10, no_cuda=False, seed=1)

下载数据集到./data/目录下:

kwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}
trainset = datasets.MNIST('../data', train=True, download=True,transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(
trainset,
batch_size=args.batch_size, shuffle=True, **kwargs)
testset= datasets.MNIST('../data', train=False, transform=transforms.ToTensor())
test_loader = torch.utils.data.DataLoader(
testset,
batch_size=args.batch_size, shuffle=True, **kwargs)
image, label = trainset[0]
print(len(trainset))
print(image.size())
image, label = testset[0]
print(len(testset))
print(image.size())

输出结果:

60000
torch.Size([1, 28, 28])
10000
torch.Size([1, 28, 28])

2定义VAE

首先我们介绍x.view方法:

x = torch.randn(4, 4)y = x.view(16)z = x.view(-1, 16)  # the size -1 is inferred from other dimensions
print(x)
print(y)
print(z)

输出结果:

 1.6154  1.1792  0.6450  1.2078
-0.4741 1.2145 0.8381 2.3532
0.2070 -0.9054 0.9262 0.6758
1.2613 0.5196 -1.7125 -0.0519
[torch.FloatTensor of size 4x4]
1.6154
1.1792
0.6450
1.2078
-0.4741
1.2145
0.8381
2.3532
0.2070
-0.9054
0.9262
0.6758
1.2613
0.5196
-1.7125
-0.0519
[torch.FloatTensor of size 16]
Columns 0 to 9
1.6154 1.1792 0.6450 1.2078 -0.4741 1.2145 0.8381 2.3532 0.2070 -0.9054 Columns 10 to 15
0.9262 0.6758 1.2613 0.5196 -1.7125 -0.0519
[torch.FloatTensor of size 1x16]

然后建立VAE模型

class VAE(nn.Module):
def __init__(self):
super(VAE, self).__init__() self.fc1 = nn.Linear(784, 400)
self.fc21 = nn.Linear(400, 20)
self.fc22 = nn.Linear(400, 20)
self.fc3 = nn.Linear(20, 400)
self.fc4 = nn.Linear(400, 784) self.relu = nn.ReLU()
self.sigmoid = nn.Sigmoid() def encode(self, x):
h1 = self.relu(self.fc1(x))
return self.fc21(h1), self.fc22(h1) def reparametrize(self, mu, logvar):
std = logvar.mul(0.5).exp_()
eps = Variable(std.data.new(std.size()).normal_())
return eps.mul(std).add_(mu) def decode(self, z):
h3 = self.relu(self.fc3(z))
return self.sigmoid(self.fc4(h3)) def forward(self, x):
mu, logvar = self.encode(x.view(-1, 784))
z = self.reparametrize(mu, logvar)
return self.decode(z), mu, logvar model = VAE()
if args.cuda:
model.cuda()

3.定义一个损失函数


reconstruction_function = nn.BCELoss()
reconstruction_function.size_average = False def loss_function(recon_x, x, mu, logvar):
BCE = reconstruction_function(recon_x, x.view(-1, 784)) # see Appendix B from VAE paper:
# Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014
# https://arxiv.org/abs/1312.6114
# 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
KLD_element = mu.pow(2).add_(logvar.exp()).mul_(-1).add_(1).add_(logvar)
KLD = torch.sum(KLD_element).mul_(-0.5) return BCE + KLD optimizer = optim.Adam(model.parameters(), lr=1e-3)

4.在训练数据上训练神经网络

我们只需要对数据迭代器进行循环,并将输入反馈到网络并进行优化。

for epoch in range(1, args.epochs + 1):
train(epoch)
test(epoch)

其中

def train(epoch):
model.train()
train_loss = 0
for batch_idx, (data, _) in enumerate(train_loader):
data = Variable(data)
if args.cuda:
data = data.cuda()
optimizer.zero_grad()
recon_batch, mu, logvar = model(data)
loss = loss_function(recon_batch, data, mu, logvar)
loss.backward()
train_loss += loss.data[0]
optimizer.step()
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader),
loss.data[0] / len(data))) print('====> Epoch: {} Average loss: {:.4f}'.format(
epoch, train_loss / len(train_loader.dataset))) def test(epoch):
model.eval()
test_loss = 0
for data, _ in test_loader:
if args.cuda:
data = data.cuda()
data = Variable(data, volatile=True)
recon_batch, mu, logvar = model(data)
test_loss += loss_function(recon_batch, data, mu, logvar).data[0] test_loss /= len(test_loader.dataset)
print('====> Test set loss: {:.4f}'.format(test_loss))

Tips:

1.直接运行pytorch examples里的代码发现library not initialized at /pytorch/torch/lib/THC/THCGeneral.c错误

解决方案:sudo rm -r ~/.nv

2.该源码实现的论文为https://arxiv.org/pdf/1312.6114.pdf

pytorch实现VAE的更多相关文章

  1. Pytorch入门之VAE

    关于自编码器的原理见另一篇博客 : 编码器AE & VAE 这里谈谈对于变分自编码器(Variational auto-encoder)即VAE的实现. 1. 稀疏编码 首先介绍一下“稀疏编码 ...

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

    import os import torch import torch.nn as nn import torch.nn.functional as F import torchvision from ...

  3. pytorch实现DCGAN、pix2pix、DiscoGAN、CycleGAN、BEGAN以及VAE

    https://github.com/sunshineatnoon/Paper-Implementations

  4. Pytorch 细节记录

    1. PyTorch进行训练和测试时指定实例化的model模式为:train/eval eg: class VAE(nn.Module): def __init__(self): super(VAE, ...

  5. 【转载】 Pytorch 细节记录

    原文地址: https://www.cnblogs.com/king-lps/p/8570021.html ---------------------------------------------- ...

  6. (转)Awesome PyTorch List

    Awesome-Pytorch-list 2018-08-10 09:25:16 This blog is copied from: https://github.com/Epsilon-Lee/Aw ...

  7. (转) The Incredible PyTorch

    转自:https://github.com/ritchieng/the-incredible-pytorch The Incredible PyTorch What is this? This is ...

  8. pytorch实现autoencoder

    关于autoencoder的内容简介可以参考这一篇博客,可以说写的是十分详细了https://sherlockliao.github.io/2017/06/24/vae/ 盗图一张,自动编码器讲述的是 ...

  9. 库、教程、论文实现,这是一份超全的PyTorch资源列表(Github 2.2K星)

    项目地址:https://github.com/bharathgs/Awesome-pytorch-list 列表结构: NLP 与语音处理 计算机视觉 概率/生成库 其他库 教程与示例 论文实现 P ...

随机推荐

  1. FreeMarker简介

    什么是 FreeMarker? FreeMarker 是一款 模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具. 它不是面向最终用 ...

  2. Django项目之小博客

    学习了几天Django,学着做了一个简易的小博客,主要用来练习Django基本的操作. 主要用到的命令和Django包.模块等: django.urls.url django.urls.import ...

  3. .NET Core 2.0 应用程序大小减少50%

    .NET Core 2.0减小体积瘦身官方工具 IL Linker. IL Linker 来源于mono的linker  https://github.com/mono/linker,目前还是预览版本 ...

  4. 模仿Spring实现注解注入

    写这个极其蛋疼,我一直在想我们用SSM写项目时,写Service和Controller的时候,会给Service和Controller私有属性,比如Service需要dao,Controller需要S ...

  5. Java后台开发必备软件(windows环境下)

    一.必备软件 1.Jdk,推荐下载最新版2.Ide,推荐 IntelliJ IDEA3.服务器,如 tomcat / jetty4.数据库终端界面,推荐 Navicat Premium(自行破解),5 ...

  6. 设置input框文字垂直居中和宽度

    input { solid #999;height:22px; background:#ffffff; line-height:22px; margin:0px; padding:0px;/*表单输入 ...

  7. 基于moco的mock server 简单应用 来玩玩吧

    提起mock大家应该就知道是干嘛用的了,再次再介绍一种简单的方式,基于moco的mock server.步骤很简单: 1. 首先,要下载个moco的jar0_1482402640757_moco-ru ...

  8. el-input监听不了回车事件

    vue使用element-ui的el-input监听不了回车事件,原因应该是element-ui自身封装了一层input标签之后,把原来的事件隐藏了,所以如下代码运行是无响应的: <el-inp ...

  9. 使用Sidecar将Node.js引入Spring Cloud

    网上看到的一篇文章,觉得写得挺好,现转载于此,以方便需要的网友查阅. 该文章介绍了非JAVA语言提供的应用集成到Spring Cloud的这样一个实现,以便我们使用其他语言作为参考. 感谢原作者分享, ...

  10. 只查看tomcat进程,不包括grep

    ps aux | grep tomcat  | grep -v "grep" | awk '{print $2}'