6-2 稀疏自动编码器--Keras实现

查看完整代码http://www.daimapi.com/neuralnetwork6_2/

该代码利用Python3实现,利用到了深度学习工具包Keras。

自编码器(AutoEncoder),即可以使用自身的高阶特征自我编码,自编码器其实也是一种神经网络,其输入和输出是一致的,借助了稀疏编码的思想,目标是使用稀疏的高阶特征重新组合来重构自己。
      如果我们对隐层单元施加稀疏性约束的话,会得到更为紧凑的表达,只有一小部分神经元会被激活。在Keras中,我们可以通过添加一个activity_regularizer达到对某层激活值进行约束的目的。
      encoded = Dense(encoding_dim, activation='relu', activity_regularizer=regularizers.l1(10e-5))(input_img)

      把多个自编码器叠起来即加深自编码器的深度,50个epoch后,损失val_loss:0.0926,比1个隐含层的自编码器要好一些。   

# -*- coding: utf-8 -*-
import numpy as np
np.random.seed(1337)  # 固定随机数,重现结果

from keras.datasets import mnist
from keras.models import Model #泛型模型
from keras.layers import Dense, Input
import matplotlib.pyplot as plt
from keras import regularizers

# X shape (60,000 28x28), y shape (10,000, )
(x_train, _), (x_test, y_test) = mnist.load_data()

# 数据预处理
x_train = x_train.astype('float32') / 255.        # 归一化
x_test = x_test.astype('float32') / 255.        # 归一化
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)

猜你喜欢

转载自blog.csdn.net/aeoob/article/details/81060156
6-2
今日推荐