栈式降噪自编码器_第十九节,去噪自编码和栈式自编码

上一节我们讲到自编码可以用于进行数据降维、数据压缩、对文字或图像提取主题并用于信息检索等。 根据所解决的问题不同 ,自编码可以有许多种不同形式的变形,例如: 去噪自编码器(DAE)、变分自编码器 (VAE)、收缩自编码器(CAE)和稀疏自编码器等 。下面我们先从去噪自编码讲起。一 去噪自编码要想取得好的特征只靠重构输入数据是不够的,在实际应用中,还需要让这些特征具有靠干扰的能力,即当输入数据发生一...
摘要由CSDN通过智能技术生成

上一节我们讲到自编码可以用于进行数据降维、数据压缩、对文字或图像提取主题并用于信息检索等。 根据所解决的问题不同 ,自编码可以有许多种不同形式的变形,例如: 去噪自编码器(DAE)、变分自编码器 (VAE)、收缩自编码器(CAE)和稀疏自编码器等 。下面我们先从去噪自编码讲起。

一 去噪自编码

要想取得好的特征只靠重构输入数据是不够的,在实际应用中,还需要让这些特征具有靠干扰的能力,即当输入数据发生一定程度的干扰时,生成的特征仍然保持不变。这时需要添加噪声来为模型增加更大的困难。在这种情况下训练出来的模型才会有更好的鲁棒性,于是就有了本节所要介绍的去噪自编码。

去噪自编码(Denoising Auto Encoder),是在自编码的基础上,训练数据加入噪声,输出的标签仍是原来的样本(没有加过噪声的),这样自编码必须学习去除噪声而获得真正的没有被噪声污染过的输入特征。因此,这就迫使编码器去学习输入信号的更具有鲁棒性的特征表达,即具有更强的泛化能力。

在实际训练中,人为加入的噪声有两种途径:

在选择训练数据集时,额外选择一些样本集以外的数据。

改变已有的样本数据集中的数据(使样本个体不完整,或通过噪声与样本进行加减乘除之类的运算,使样本数据发生变化)

二 使用去燥自编码提取MNIST特征

#-*- coding: utf-8 -*-

"""Created on Sun May 27 17:49:18 2018

@author: zy"""

importtensorflow as tfimportnumpy as npimportmatplotlib.pyplot as pltfrom tensorflow.examples.tutorials.mnist importinput_data

mnist= input_data.read_data_sets('MNIST-data',one_hot=True)print(type(mnist)) #

print('Training data shape:',mnist.train.images.shape) #Training data shape: (55000, 784)

print('Test data shape:',mnist.test.images.shape) #Test data shape: (10000, 784)

print('Validation data shape:',mnist.validation.images.shape) #Validation data shape: (5000, 784)

print('Training label shape:',mnist.train.labels.shape) #Training label shape: (55000, 10)

train_X=mnist.train.images

train_Y=mnist.train.labels

test_X=mnist.test.images

test_Y=mnist.test.labelsdefdenoising_auto_encoder():'''去燥自编码器 784-256-256-784

对MNIST原始输入图片加入噪声,在自编码网络中进行训练,以得到抗干扰更强的特征提取模型'''n_input= 784 #输入节点数

n_hidden = 256 #隐藏层节点个数

learning_rate = 0.01 #学习率

training_epochs = 20 #迭代轮数

batch_size = 256 #小批量数量大小

display_epoch = 2show_num= 10 #显示的图片个数

#定义占位符

input_x = tf.placeholder(dtype=tf.float32,shape=[None,n_input])

input_y= tf.placeholder(dtype=tf.float32,shape=[None,n_input])

keep_prob= tf.placeholder(dtype=tf.float32)#定义参数

weights ={'h1':tf.Variable(tf.random_normal(shape=[n_input,n_hidden],stddev=0.1)),'h2':tf.Variable(tf.random_normal(shape=[n_hidden,n_hidden],stddev=0.1)),'out':tf.Variable(tf.random_normal(shape=[n_hidden,n_input],stddev=0.1))

}

biases={'b1':tf.Variable(tf.zeros(shape=[n_hidden])),'b2':tf.Variable(tf.zeros(shape=[n_hidden])),'out':tf.Variable(tf.zeros(shape=[n_input]))

}#网络模型 去燥自编码

h1 = tf.nn.sigmoid(tf.add(tf.matmul(input_x,weights['h1']),biases['b1']))

h1=tf.nn.dropout(h1,keep_prob)

h2= tf.nn.sigmoid(tf.add(tf.matmul(h1,weights['h2']),biases['b2']))

h2=tf.nn.dropout(h2,keep_prob)

pred= tf.nn.sigmoid(tf.add(tf.matmul(h2,weights['out']),biases['out']))#计算代价

cost = tf.reduce_mean((pred-input_y)**2)#定义优化器

#train = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)

train =tf.train.AdamOptimizer(learning_rate).minimize(cost)

num_batch= int(np.ceil(mnist.train.num_examples /batch_size))#开始训练

with tf.Session() as sess:

sess.run(tf.global_variables_initializer())print('开始训练')for epoch inrange(training_epochs):

total_cost= 0.0

for i inrange(num_batch):

batch_x,batch_y=mnist.train.next_batch(batch_size)#添加噪声 每次取出来一批次的数据,将输入数据的每一个像素都加上0.3倍的高斯噪声

batch_x_noise = batch_x + 0.3*np.random.randn(batch_size,784) #标准正态分布

_,loss = sess.run([train,cost],feed_dict={input_x:batch_x_noise,input_y:batch_x,keep_prob:1.0})

total_cost+=loss#打印信息

if epoch % display_epoch ==0:print('Epoch {0}/{1} average cost {2}'.format(epoch,training_epochs,total_cost/num_batch))print('训练完成')#数据可视化

test_noisy= mnist.test.images[:show_num] + 0.3*np.random.randn(show_num,784)

reconstruction= sess.run(pred,feed_dict = {input_x:test_noisy,keep_prob:1.0})

plt.figure(figsize=(1.0*show_num,1*2))for i inrange(show_num):#原始图像

plt.subplot(3,show_num,i+1)

plt.imshow(np.reshape(mnist.test.images[i],(28,28)),cmap='gray')

plt.axis('off')#加入噪声后的图像

plt.subplot(3,show_num,i+show_num*1+1)

plt.imshow(np.reshape(test_noisy[i],(28,28)),cmap='gray')

plt.axis('off')#去燥自编码器输出图像

plt.subplot(3,show_num,i+show_num*2+1)

plt.imshow(np.reshape(reconstruction[i],(28,28)),cmap='gray')

plt.axis('off')

plt.show()#测试鲁棒性 为了测试模型的鲁棒性,我们换一种噪声方式,然后再生成一个样本测试效果

plt.figure(figsize=(2.4*3,1*2))#生成一个0~mnist.test.images.shape[0]的随机整数

randidx = np.random.randint(test_X.shape[0],size=1)

orgvec= test_X[randidx] #1x784

#获取标签

label = np.argmax(test_Y[randidx],1)print('Label is %d'%(label))#噪声类型 对原始图像加入噪声

print('Salt and Paper Noise')

noisyvec= test_X[randidx] #1 x 784

#噪声点所占的比重

rate = 0.15

#生成噪声点索引

noiseidx = np.random.randint(test_X.shape[1],size=int(test_X.shape[1]*rate)).astype(np.int32)#对这些点像素进行反向

for i innoiseidx:

noisyvec[0,i]= 1.0 -noisyvec[0,i]#噪声图像自编码器输出

outvec = sess.run(pred,feed_dict={input_x:noisyvec,keep_prob:1.0})

outimg= np.reshape(outvec,(28,28))#可视化

plt.subplot(1,3,1)

plt.imshow(np.reshape(orgvec,(28,28)),cmap='gray')

plt.title('Original Image')

plt.axis('off')

plt.subplot(1,3,2)

plt.imshow(np.reshape(noisyvec,(28,28)),cmap='gray')

plt.title('Input Image')

plt.axis('off')

plt.subplot(1,3,3)

plt.imshow(outimg,cmap='gray')

plt.title('Reconstructed Image')

plt.axis('off')if __name__ == '__main__':

denoising_auto_encoder()

上面我们在训练的时候给keep_prob传入的值为1.0,运行结果如下:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值