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. myeclipse新建javaweb项目,并部署到tomcat

    myeclipse使用的版本: 新建web项目: File-->New-->Web Project,输入项目名称,选择J2EE规范. 完成后: JRE System Library是只要做 ...

  2. dedecms织梦的不同栏目调用不同banner图的方法

    在做织梦站的时候我们会有不同的栏目,比如联系我们,产品中心等等,banner也不一样,方法如下: 我们可以使用织梦的顶级栏目ID标签,把图片命名成顶级栏目typeid ,代码如下: <img s ...

  3. protobuf使用详解

    https://blog.csdn.net/skh2015java/article/details/78404235 原文地址:http://blog.csdn.net/lyjshen/article ...

  4. php扩展之Yar

    Yar 是一个轻量级, 高效的RPC框架, 它提供了一种简单方法来让PHP项目之间可以互相远程调用对方的本地方法. 并且Yar也提供了并行调用的能力. 可以支持同时调用多个远程服务的方法. 情况: 有 ...

  5. HTTP协议与TCP/IP协议

    OSI 是7层         TCP/IP 协议是 4层. OIS 包括的层 从底到上依次为 1.物理层 2.数据链路层 3.网络层 4.传输层 5.会话层 6.表示层 7.应用层 TCP/IP  ...

  6. Linux(Ubuntu)使用日记------Mysql编码(utf-8)的设置

    Mysq版本:5.7.21 操作系统:Linux(Ubuntu) 整个操作的基本思路如下(包括问题的解决思路,想要直接解决问题的可以先看最后的命令总结) 检查mysql编码 找到Mysql的配置文件 ...

  7. synchronized和lock有什么区别?

    一.原始构成 synchronized是关键字属于JVM层面,monitorenter(底层是通过monitor对象来完成,其实wait/notify等方法也依赖monitor对象只有在同步代码块和同 ...

  8. Go语言中Loop的注意点

    Go语言和其他语言不一样,它只有一种循环方式,就是for语句 可以参考如下公式: for initialisation; condition; post{ //Do Something } 执行顺序 ...

  9. win10 nginx

    下载后运行报错 nginx: [emerg] bind() to 0.0.0.0:80 failed (10013: An attempt was made to access a socket in ...

  10. KEIL之工程单独文件属性修改

    @2019-04-29 [小记] 可以设置文件是否参与编译.内存分配.宏定义等属性设置