Keras——用Keras搭建自编码神经网络(AutoEncoder)

1.前言

自编码,简单来说就是把输入数据进行一个压缩和解压缩的过程。 原来有很多 Feature,压缩成几个来代表原来的数据,解压之后恢复成原来的维度,再和原数据进行比较。

它是一种非监督算法,只需要输入数据,解压缩之后的结果与原数据本身进行比较。

今天要做的事情是把 datasets.mnist 数据的 28×28=784 维的数据,压缩成 2 维的数据,然后在一个二维空间中可视化出分类的效果

2.用Keras搭建自编码神经网络

2.1.导入必要模块

import numpy as np
from keras.datasets import mnist
from keras.models import Model
from keras.layers import Dense, Input
import matplotlib.pyplot as plt
np.random.seed(42)

2.2.数据预处理

x_train = x_train.astype('float')/255. - 0.5         #归一化
x_test = x_test.astype('float')/255. - 0.5
x_train = x_train.reshape((x_train.shape[0],-1))    
x_test = x_test.reshape((x_test.shape[0]),-1)
print(x_train.shape)
print(x_test.shape)

在这里插入图片描述

2.3.搭建模型

encoding_dim,要压缩成的维度。

接下来是建立 encoded 和 decoded ,再用 autoencoder 把二者组建在一起。训练时用 autoencoder。

encoded 用4层 Dense 全联接层,激活函数用 relu,输入的维度就是前一步定义的 input_img。

接下来定义下一层,它的输出维度是64,输入是上一层的输出结果。
在最后一层,我们定义它的输出维度就是想要的 encoding_dim=2。

解压的环节,它的过程和压缩的过程是正好相反的。相对应层的激活函数也是一样的,不过在解压的最后一层用到的激活函数是 tanh。 因为输入值是由 -0.5 到 0.5 这个范围,在最后一层用这个激活函数的时候,它的输出是 -1 到 1,可以是作为一个很好的对应。

encoding_dim = 2

#自编码器
input_img = Input(shape=(784,))    #返回一个张量

encoded = Dense(128,activation='relu')(input_img)
encoded = Dense(64,activation='relu')(encoded)
encoded = Dense(10,activation='relu')(encoded)
encoder_output = Dense(encoding_dim)(encoded)

decoded = Dense(10,activation='relu')(encoder_output)
decoded = Dense(64,activation='relu')(decoded)
decoded = Dense(128,activation='relu')(decoded)
decoded = Dense(784,activation='tanh')(decoded)

2.4.实例化并激活模型

接下来直接用 Model 这个模块来组建模型,输入就是图片,输出是解压的最后的结果。

当我们想要看由 784 压缩到 2维后,这个结果是什么样的时候,也可以只单独组建压缩的板块,此时它的输入是图片,输出是压缩环节的最后结果。

接下来是编译自编码这个模型,优化器用的是 adam,损失函数用的是 mse。

autoencoder = Model(input = input_img, output=decoded)    #实例化
encoder = Model(input=input_img, output=encoder_output)

autoencoder.compile(
    optimizer = 'adam',
    loss = 'mse'
)

2.5.训练

接下来训练自编码模型,注意它的输入和输出是一样的,都是训练集的 X。

autoencoder.fit(x_train,x_train,
                epochs = 20,
                batch_size = 256,
                shuffle = True)

在这里插入图片描述

2.6.可视化

最后看到可视化的结果,自编码模型可以把这几个数字给区分开来,我们可以用自编码这个过程来作为一个特征压缩的方法,和PCA的功能一样,效果要比它好一些,因为它是非线性的结构。

encoded_imgs = encoder.predict(x_test)
plt.scatter(encoded_imgs[:,0],encoded_imgs[:,1],c=y_test)
plt.colorbar()
plt.show()

在这里插入图片描述

Code provided by Ruslan Salakhutdinov and Geoff Hinton Permission is granted for anyone to copy, use, modify, or distribute this program and accompanying programs and documents for any purpose, provided this copyright notice is retained and prominently displayed, along with a note saying that the original programs are available from our web page. The programs and documents are distributed without any warranty, express or implied. As the programs were written for research purposes only, they have not been tested to the degree that would be advisable in any important application. All use of these programs is entirely at the user's own risk. How to make it work: 1. Create a separate directory and download all these files into the same directory 2. Download from http://yann.lecun.com/exdb/mnist the following 4 files: o train-images-idx3-ubyte.gz o train-labels-idx1-ubyte.gz o t10k-images-idx3-ubyte.gz o t10k-labels-idx1-ubyte.gz 3. Unzip these 4 files by executing: o gunzip train-images-idx3-ubyte.gz o gunzip train-labels-idx1-ubyte.gz o gunzip t10k-images-idx3-ubyte.gz o gunzip t10k-labels-idx1-ubyte.gz If unzipping with WinZip, make sure the file names have not been changed by Winzip. 4. Download Conjugate Gradient code minimize.m 5. Download Autoencoder_Code.tar which contains 13 files OR download each of the following 13 files separately for training an autoencoder and a classification model: o mnistdeepauto.m Main file for training deep autoencoder o mnistclassify.m Main file for training classification model o converter.m Converts raw MNIST digits into matlab format o rbm.m Training RBM with binary hidden and binary visible units o rbmhidlinear.m Training RBM with Gaussian hidden and binary visible units o backprop.m Backpropagation for fine-tuning an autoencoder o backpropclassify.m Backpropagation for classification using "encoder" network o CG_MNIST.m Conjugate Gradient optimization for fine-tuning an autoencoder o CG_CLASSIFY_INIT.m Co
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值