###仅为自己练习,没有其他用途

  1 import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np # torch.manual_seed(1) # reproducible # Hyper Parameters
EPOCH = 10
BATCH_SIZE = 64
LR = 0.005 # learning rate
DOWNLOAD_MNIST = False
N_TEST_IMG = 5 # Mnist digits dataset
train_data = torchvision.datasets.MNIST(
root='./mnist/',
train=True, # this is training data
transform=torchvision.transforms.ToTensor(), # Converts a PIL.Image or numpy.ndarray to
# torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]
download=DOWNLOAD_MNIST, # download it if you don't have it
) # plot one example
print(train_data.train_data.size()) # (60000, 28, 28)
print(train_data.train_labels.size()) # (60000)
plt.imshow(train_data.train_data[2].numpy(), cmap='gray')
plt.title('%i' % train_data.train_labels[2])
plt.show() # Data Loader for easy mini-batch return in training, the image batch shape will be (50, 1, 28, 28)
train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True) class AutoEncoder(nn.Module):
def __init__(self):
super(AutoEncoder, self).__init__() self.encoder = nn.Sequential(
nn.Linear(28*28, 128),
nn.Tanh(),
nn.Linear(128, 64),
nn.Tanh(),
nn.Linear(64, 12),
nn.Tanh(),
nn.Linear(12, 3), # compress to 3 features which can be visualized in plt
)
self.decoder = nn.Sequential(
nn.Linear(3, 12),
nn.Tanh(),
nn.Linear(12, 64),
nn.Tanh(),
nn.Linear(64, 128),
nn.Tanh(),
nn.Linear(128, 28*28),
nn.Sigmoid(), # compress to a range (0, 1)
) def forward(self, x):
encoded = self.encoder(x)
decoded = self.decoder(encoded)
return encoded, decoded autoencoder = AutoEncoder() optimizer = torch.optim.Adam(autoencoder.parameters(), lr=LR)
loss_func = nn.MSELoss() # initialize figure
f, a = plt.subplots(2, N_TEST_IMG, figsize=(5, 2))
plt.ion() # continuously plot # original data (first row) for viewing
view_data = train_data.train_data[:N_TEST_IMG].view(-1, 28*28).type(torch.FloatTensor)/255.
for i in range(N_TEST_IMG):
a[0][i].imshow(np.reshape(view_data.data.numpy()[i], (28, 28)), cmap='gray'); a[0][i].set_xticks(()); a[0][i].set_yticks(()) for epoch in range(EPOCH):
for step, (x, b_label) in enumerate(train_loader):
b_x = x.view(-1, 28*28) # batch x, shape (batch, 28*28)
b_y = x.view(-1, 28*28) # batch y, shape (batch, 28*28) encoded, decoded = autoencoder(b_x) loss = loss_func(decoded, b_y) # mean square error
optimizer.zero_grad() # clear gradients for this training step
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients if step % 100 == 0:
print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy()) # plotting decoded image (second row)
_, decoded_data = autoencoder(view_data)
for i in range(N_TEST_IMG):
a[1][i].clear()
a[1][i].imshow(np.reshape(decoded_data.data.numpy()[i], (28, 28)), cmap='gray')
a[1][i].set_xticks(()); a[1][i].set_yticks(())
plt.draw(); plt.pause(0.05) plt.ioff()
plt.show() # visualize in 3D plot
view_data = train_data.train_data[:200].view(-1, 28*28).type(torch.FloatTensor)/255.
encoded_data, _ = autoencoder(view_data)
fig = plt.figure(2); ax = Axes3D(fig)
X, Y, Z = encoded_data.data[:, 0].numpy(), encoded_data.data[:, 1].numpy(), encoded_data.data[:, 2].numpy()
values = train_data.train_labels[:200].numpy()
for x, y, z, s in zip(X, Y, Z, values):
c = cm.rainbow(int(255*s/9)); ax.text(x, y, z, s, backgroundcolor=c)
ax.set_xlim(X.min(), X.max()); ax.set_ylim(Y.min(), Y.max()); ax.set_zlim(Z.min(), Z.max())
plt.show()

pytoch之 encoder,decoder的更多相关文章

  1. 自定义Encoder/Decoder进行对象传递

    转载:http://blog.csdn.net/top_code/article/details/50901623 在上一篇文章中,我们使用Netty4本身自带的ObjectDecoder,Objec ...

  2. 比sun.misc.Encoder()/Decoder()的base64更高效的mxBase64算法

    package com.mxgraph.online; import java.util.Arrays; /** A very fast and memory efficient class to e ...

  3. Netty自定义Encoder/Decoder进行对象传递

    转载:http://blog.csdn.net/top_code/article/details/50901623 在上一篇文章中,我们使用Netty4本身自带的ObjectDecoder,Objec ...

  4. Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation

    1.主要完成的任务是能够将英文转译为法文,使用了一个encoder-decoder模型,在encoder的RNN模型中是将序列转化为一个向量.在decoder中是将向量转化为输出序列,使用encode ...

  5. Transformer模型---encoder

    一.简介 论文链接:<Attention is all you need> 由google团队在2017年发表于NIPS,Transformer 是一种新的.基于 attention 机制 ...

  6. pytorch-- Attention Mechanism

    1. paper: Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translat ...

  7. JavaScript资源大全中文版(Awesome最新版)

    Awesome系列的JavaScript资源整理.awesome-javascript是sorrycc发起维护的 JS 资源列表,内容包括:包管理器.加载器.测试框架.运行器.QA.MVC框架和库.模 ...

  8. Java DNS查询内部实现

    源码分析 在Java中,DNS相关的操作都是通过通过InetAddress提供的API实现的.比如查询域名对应的IP地址: String dottedQuadIpAddress = InetAddre ...

  9. helios架构详解(一)服务器端架构

    看了“菜鸟耕地”的”.NET开源高性能Socket通信中间件Helios介绍及演示“,觉得这个东西不错.但是由于没有网络编程知识,所以高性能部分我就讲不出来了,主要是想根据开源代码跟大家分享下Heli ...

随机推荐

  1. laravel配置加解密

    基于安全考虑,我们php项目配置文件中密码应该是加密的,laravel中也提供了OpenSSL 的 AES-256-CBC 来进行加密 但是如果我们项目配置的是其他加密方式,且希望以最少的改动实现读取 ...

  2. [AI开发]小型数据集解决实际工程问题——交通拥堵、交通事故实时告警

    这篇文章其实主要是想介绍在深度学习过程中如何使用小型数据集,这种数据集样本数量一般在1000以下,有时候甚至只有几百.一般提到神经网络,大家都会说数据量越丰富,准确性越高,但是实际工作中,可能收集不了 ...

  3. 重拾c++第一天(1):环境配置

    时过多年,c++基本不记得了,故在此记录相关重拾记录. 学习语言第一步当然是环境配置了(笑),由于暂无用c++进行大型项目开发的需求,所以先下载dev进行过渡. 安装过程非常简单,值得注意的是配置时选 ...

  4. 解决浮点运算精度不准确,BigDecimal 加减乘除

    package com.kflh.boxApi.utils.util; import java.math.BigDecimal; /** * @program: BoxApi * @descripti ...

  5. 代码写不对队-Beta冲刺版本

    代码写不对队:Beta冲刺版本 这个作业属于哪个课程 http://edu.cnblogs.com/campus/xnsy/GeographicInformationScience/homework ...

  6. sqli_labs学习笔记(一)Less-21~Less-37

    续上,开门见山 Less-21 Cookie Injection- Error Based- complex - string ( 基于错误的复杂的字符型Cookie注入) 登录后页面 圈出来的地方显 ...

  7. 自定义BeanDefinitionRegistryPostProcessor

    自定义BeanDefinitionRegistryPostProcessor 概述 BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProce ...

  8. 自动化运维之Ansible入门

    Ansible简介 Ansible是什么? Ansible 简单的说是一个配置管理系统(ConfiGuration Management System).你只需要可以使用ssh访问你的服务器或设备.它 ...

  9. 强大的 Python 任务自动化工具!invoke 十分钟入门指南

    接着前面的<tox 教程>,以及刚翻译好的<nox文档>,我们继续聊聊 Python 任务自动化的话题. nox 的作者在去年的 Pycon US 上,做了一场题为<Br ...

  10. CDH 离线安装 CM

    CDH支持Yum包,Tar包,RPM包,Cloudera Manager(CM)四种安装方式 Cloudera Manager(CM) 用于CDH集群管理,可进行节点安装,配置,服务管理等,提供Web ...