VAE论文学习
intractable棘手的,难处理的 posterior distributions后验分布 directed probabilistic有向概率
approximate inference近似推理 multivariate Gaussian多元高斯 diagonal对角 maximum likelihood极大似然
参考:https://blog.csdn.net/yao52119471/article/details/84893634
VAE论文所在讲的问题是:
我们现在就是想要训练一个模型P(x),并求出其参数Θ:

通过极大似然估计求其参数
Variational Inference
在论文中P(x)模型会被拆分成两部分,一部分由数据x生成潜在向量z,即pθ(z|X);一部分从z重新在重构数据x,即pθ(X|z)
实现过程则是希望能够使用一个qΦ(z|X)模型去近似pθ(z|X),然后作为模型的Encoder;后半部分pθ(X|z)则作为Decoder,Φ/θ表示参数,实现一种同时学习识别模型参数φ和参数θ的生成模型的方法,推导过程为:


现在问题就在于怎么进行求导,因为现在模型已经不是一个完整的P(x) = pθ(z|X) + pθ(X|z),现在变成了P(x) = qΦ(z|X) + pθ(X|z),那么如果对Φ求导就会变成一个问题,因此论文中就提出了一个reparameterization trick方法:

取样于一个标准正态分布来采样z,以此将qΦ(z|X) 和pθ(X|z)两个子模型通过z连接在了一起
最终的目标函数为:

因此目标函数 = 输入和输出x求MSELoss - KL(qΦ(z|X) || pθ(z))
在论文上对式子最后的KL散度 -KL(qΦ(z|X) || pθ(z))的计算有简化为:

多维KL散度的推导可见:KL散度
假设pθ(z)服从标准正态分布,采样ε服从标准正态分布满足该假设

简单代码实现:
import torch
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
import torchvision
from torchvision import transforms
import torch.optim as optim
from torch import nn
import matplotlib.pyplot as plt class Encoder(torch.nn.Module):
def __init__(self, D_in, H, D_out):
super(Encoder, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out) def forward(self, x):
x = F.relu(self.linear1(x))
return F.relu(self.linear2(x)) class Decoder(torch.nn.Module):
def __init__(self, D_in, H, D_out):
super(Decoder, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out) def forward(self, x):
x = F.relu(self.linear1(x))
return F.relu(self.linear2(x)) class VAE(torch.nn.Module):
latent_dim = def __init__(self, encoder, decoder):
super(VAE, self).__init__()
self.encoder = encoder
self.decoder = decoder
self._enc_mu = torch.nn.Linear(, )
self._enc_log_sigma = torch.nn.Linear(, ) def _sample_latent(self, h_enc):
"""
Return the latent normal sample z ~ N(mu, sigma^)
"""
mu = self._enc_mu(h_enc)
log_sigma = self._enc_log_sigma(h_enc) #得到的值是loge(sigma)
sigma = torch.exp(log_sigma) # = e^loge(sigma) = sigma
#从均匀分布中取样
std_z = torch.from_numpy(np.random.normal(, , size=sigma.size())).float() self.z_mean = mu
self.z_sigma = sigma return mu + sigma * Variable(std_z, requires_grad=False) # Reparameterization trick def forward(self, state):
h_enc = self.encoder(state)
z = self._sample_latent(h_enc)
return self.decoder(z) # 计算KL散度的公式
def latent_loss(z_mean, z_stddev):
mean_sq = z_mean * z_mean
stddev_sq = z_stddev * z_stddev
return 0.5 * torch.mean(mean_sq + stddev_sq - torch.log(stddev_sq) - ) if __name__ == '__main__': input_dim = *
batch_size = transform = transforms.Compose(
[transforms.ToTensor()])
mnist = torchvision.datasets.MNIST('./', download=True, transform=transform) dataloader = torch.utils.data.DataLoader(mnist, batch_size=batch_size,
shuffle=True, num_workers=) print('Number of samples: ', len(mnist)) encoder = Encoder(input_dim, , )
decoder = Decoder(, , input_dim)
vae = VAE(encoder, decoder) criterion = nn.MSELoss() optimizer = optim.Adam(vae.parameters(), lr=0.0001)
l = None
for epoch in range():
for i, data in enumerate(dataloader, ):
inputs, classes = data
inputs, classes = Variable(inputs.resize_(batch_size, input_dim)), Variable(classes)
optimizer.zero_grad()
dec = vae(inputs)
ll = latent_loss(vae.z_mean, vae.z_sigma)
loss = criterion(dec, inputs) + ll
loss.backward()
optimizer.step()
l = loss.data[]
print(epoch, l) plt.imshow(vae(inputs).data[].numpy().reshape(, ), cmap='gray')
plt.show(block=True)
VAE论文学习的更多相关文章
- Faster RCNN论文学习
Faster R-CNN在Fast R-CNN的基础上的改进就是不再使用选择性搜索方法来提取框,效率慢,而是使用RPN网络来取代选择性搜索方法,不仅提高了速度,精确度也更高了 Faster R-CNN ...
- 《Explaining and harnessing adversarial examples》 论文学习报告
<Explaining and harnessing adversarial examples> 论文学习报告 组员:裴建新 赖妍菱 周子玉 2020-03-27 1 背景 Sz ...
- 论文学习笔记 - 高光谱 和 LiDAR 融合分类合集
A³CLNN: Spatial, Spectral and Multiscale Attention ConvLSTM Neural Network for Multisource Remote Se ...
- Apache Calcite 论文学习笔记
特别声明:本文来源于掘金,"预留"发表的[Apache Calcite 论文学习笔记](https://juejin.im/post/5d2ed6a96fb9a07eea32a6f ...
- FactorVAE论文学习-1
Disentangling by Factorising 我们定义和解决了从变量的独立因素生成的数据的解耦表征的无监督学习问题.我们提出了FactorVAE方法,通过鼓励表征的分布因素化且在维度上独立 ...
- GoogleNet:inceptionV3论文学习
Rethinking the Inception Architecture for Computer Vision 论文地址:https://arxiv.org/abs/1512.00567 Abst ...
- IEEE Trans 2008 Gradient Pursuits论文学习
之前所学习的论文中求解稀疏解的时候一般采用的都是最小二乘方法进行计算,为了降低计算复杂度和减少内存,这篇论文梯度追踪,属于贪婪算法中一种.主要为三种:梯度(gradient).共轭梯度(conjuga ...
- Raft论文学习笔记
先附上论文链接 https://pdos.csail.mit.edu/6.824/papers/raft-extended.pdf 最近在自学MIT的6.824分布式课程,找到两个比较好的githu ...
- 论文学习-系统评估卷积神经网络各项超参数设计的影响-Systematic evaluation of CNN advances on the ImageNet
博客:blog.shinelee.me | 博客园 | CSDN 写在前面 论文状态:Published in CVIU Volume 161 Issue C, August 2017 论文地址:ht ...
随机推荐
- java基础(7)---IO流
一.FileWriter 导包:import java.io.FileWriter 覆盖写入: 追加写入: 写数据换行: write方法重载: 二.编码: 三.FileReader: read重载 ...
- 51nod 2485 小b重排字符串
小b有一个字符串S,现在她希望重排列S,使得S中相邻字符不同. 请你判断小b是否可能成功. 样例解释:将"aab"重排为"aba"即可. 收起 输入 输入一 ...
- 《Exception团队》第七次作业:团队项目设计完善&编码
一.项目基本介绍 项目 内容 这个作业属于哪个课程 任课教师博客主页链接 这个作业的要求在哪里 作业链接地址 团队名称 Exception 作业学习目标 1.掌握软件编码实现的工程要求 作业任务 1. ...
- attention speech recognition
Attention:是一种权重向量或矩阵,其往往用在Encoder-Decoder架构中,其权重越大,表示的context对输出越重要.计算方式有很多变种,但是核心都是通过神经网络学习而得到对应的权重 ...
- Vue 项目目录结构分析
Vue项目目录结构分析 ├── v-proj | ├── node_modules // 当前项目所有依赖,一般不可以移植给其他电脑环境 | ├── public | | ├── favicon.ic ...
- 洛谷 P2296 寻找道路 题解
每日一题 day42 打卡 Analysis 首先,预处理,把每条边反向. 从终点开始bfs,标记从终点开始可以走到的点. 第二步,枚举每一个点,如果这个点没有被标记,则枚举它的每一条出边(反向后的) ...
- Oracle row_number() over() 分析函数--取出最新数据
语法格式:row_number() over(partition by 分组列 order by 排序列 desc) 一个很简单的例子 1,先做好准备 create table test1( id v ...
- YAML_10 把监听端口是8080的Apache服务全部停止
ansible]# vim ad.yml --- - hosts: cache remote_user: root tasks: - shell: netstat -atunlp | ...
- RookeyFrame Bug 线上创建的DLL被删除了 模块无法删除 临时解决
不知道什么情况 在线创建模块,DLL被删除了,但是模块的相关数据无法删除.可以按照下面的方法临时用一下. 产生这个的原因,好像是Config里面的NeedInit一直都是true,没有改为false, ...
- Cogs 376. [IOI2002]任务安排(后效性DP)
[IOI2002]任务安排 ★☆ 输入文件:batch.in 输出文件:batch.out 简单对比 时间限制:1 s 内存限制:128 MB N个任务排成一个序列在一台机器上等待完成(顺序不得改变) ...