import torch
from torch import nn
import numpy as np
import matplotlib.pyplot as plt
import torch.utils.data as Data
import torchvision
from mpl_toolkits.mplot3d import Axes3D #画3D图
from matplotlib import cm
# Hyper Parameters
EPOCH=10
BATCH_SIZE=64
LR = 0.005 # learning rate
DOWNLOAD_MNIST=False
N_TEST_IMG=5 train_data=torchvision.datasets.MNIST(
root='./mnist/',
train=True,
transform=torchvision.transforms.ToTensor(),
download=DOWNLOAD_MNIST
) 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),
)
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() ) def forward(self, x ):
encoder=self.encoder(x)
decoder=self.decoder(encoder)
return encoder,decoder AutoEncoder = AutoEncoder()
# print(AutoEncoder) optimizer = torch.optim.Adam(AutoEncoder.parameters(), lr=LR) # optimize all cnn parameters
loss_func = nn.MSELoss() f,a=plt.subplots(2,N_TEST_IMG,figsize=(5,2)) plt.ion() # continuously plot 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)
b_y=x.view(-1,28*28)
encoded, decoded = AutoEncoder(b_x)
loss=loss_func(decoded,b_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if step%100==0:
print('Epoch:|',epoch,'train loss:%0.4f'%loss.data.numpy())
_,decoded_data=AutoEncoder(view_data)
for i in range(N_TEST_IMG):
a[1][i].clear()
a[1][i].imshow(np.reshape(decoded.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() 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()

选出五张图片做测试。

图像分为5*2显示,上面一行是原始图像,下面一行为编码和解码后的图像。

encode与decode的更多相关文章

  1. [LeetCode] Encode and Decode Strings 加码解码字符串

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

  2. 【python】python新手必碰到的问题---encode与decode,中文乱码[转]

    转自:http://blog.csdn.net/a921800467b/article/details/8579510 为什么会报错“UnicodeEncodeError:'ascii' codec ...

  3. LeetCode Encode and Decode Strings

    原题链接在这里:https://leetcode.com/problems/encode-and-decode-strings/ 题目: Design an algorithm to encode a ...

  4. Encode and Decode Strings

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

  5. encode和decode

    Python字符串的encode与decode研究心得乱码问题解决方法 为什么会报错“UnicodeEncodeError: 'ascii' codec can't encode characters ...

  6. 【python】浅谈encode和decode

    对于encode和decode,笔者也是根据自己的理解,有不对的地方还请多多指点. 编码的理解: 1.编码:utf-8,utf-16,gbk,gb2312,gb18030等,编码为了便于理解,可以把它 ...

  7. 271. Encode and Decode Strings

    题目: Design an algorithm to encode a list of strings to a string. The encoded string is then sent ove ...

  8. [LeetCode#271] Encode and Decode Strings

    Problem: Design an algorithm to encode a list of strings to a string. The encoded string is then sen ...

  9. Encode and Decode Strings 解答

    Question Design an algorithm to encode a list of strings to a string. The encoded string is then sen ...

  10. python encode和decode函数说明【转载】

    python encode和decode函数说明 字符串编码常用类型:utf-8,gb2312,cp936,gbk等. python中,我们使用decode()和encode()来进行解码和编码 在p ...

随机推荐

  1. Tutorial 02_熟悉常用的HDFS操作

    Shell命令实现: (1)向HDFS 中上传任意文本文件,如果指定的文件在HDFS 中已经存在,则由用户来指定是追加到原有文件末尾还是覆盖原有的文件: (2) 从HDFS 中下载指定文件,如果本地文 ...

  2. Django(二)路由系统、视图、模板

    大纲 一.内容概要: 二.上节回顾 三.Django 视图–views  1.获取用户多个数据及文件上传  2.FBV 和 CBV  3.装饰器 四.Django模板补充  - Django模板语言循 ...

  3. Linux学习之路4——文件IO打开、创建、读写操作

    1.使用man 2 open.man 2 creat.man 2 write.man 2 read命令获取头文件 语法: int open(const char *pathname, int flag ...

  4. Linux下一些简单常用命令的总结

    Cent os常用命令 查看当前目录信息: l s a:显示所有包括隐藏文件 l :列表显示数据 h:显示数据大小 查看命令帮助: XXX --help[比如:l shel p] 清除控制台信息: c ...

  5. Error:Failed to resolve: com.android.support.constraint:constraint-layout:1.0.2

    可以换个maven库: allprojects { repositories { jcenter() //maven { url "https://jitpack.io" } ma ...

  6. luogu P1659 [国家集训队]拉拉队排练

    唔....话说好久没有发布题解了(手痒痒了 首先特别鸣谢lykkk大佬今天下午教我Manacher算法,甚是感谢 为了体现学习成果,写一篇蒟蒻版的题解(大佬勿喷 言归正传 题面——>在这儿 首先 ...

  7. Windows Subsystem for Linux 环境变量

    WSL(Windows Subsystem for Linux )的环境变量是包含Linux子系统和Windows系统的,测试如下: wy@WY-PC:/mnt/c/Windows/System32$ ...

  8. 告别回调,拥抱async await

    之前使用jquery中ajax,请求的结果需要写在回调函数里面,后面接触到了axios/fetch,使用了es6中Promise进行封装,这种链式结构调用,看起来比之前直观,可是还是没有解决回调的问题 ...

  9. PWN! 第一次测试答案及讲解

    题目链接:https://vjudge.net/contest/279567#overview 题目密码:190118 1.A+B:(考察点:EOF输入.加法运算) Topic: Calculate ...

  10. java-关于java_home配置,classpath配置和javac,java命令,javac编译器,和java虚拟机之间的关系

    在每个人学习java的第一步,都是安装jdk ,jre,配置java_home,classpath,path. 为什么要做这些?在阅读java-core的时候,看到了原理,p141. 一 关于类的共享 ...