本例为一个简单的自编码模型,让784维只通过一层256维。将原始的数据进行一些变换,每个像素点都乘以一个高斯噪声,然后再输出的位置仍然使用原始的输入样本,这样迫使网络在提取特征的同时将噪声去掉。为了防止其过拟合,还需要加入Dropout层。
实例描述
对MNIST集原始输入图片加入噪声,在自编码网络中进行训练,以得到抗干扰更强的特征提取模型。
1.引入头文件,创建网络模型及定义学习参数变量
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
#导入数据集
mnist = input_data.read_data_sets("/data/", one_hot=True)
#加载图片和标签
train_X = mnist.train.images
train_Y = mnist.train.labels
test_X = mnist.test.images
test_Y = mnist.test.labels
#定义每层维度
n_input = 784
n_hidden_1 = 256
#占位符
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_input])
dropout_keep_prob = tf.placeholder("float")
#学习参数
weights = {
'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_1])),
'out': tf.Variable(tf.random_normal([n_hidden_1, n_input]))
}
biases = {
'b1': tf.Variable(tf.zeros([n_hidden_1])),
'b2': tf.Variable(tf.zeros([n_hidden_1])),
'out': tf.Variable(tf.zeros([n_input]))
}
#网络模型
def denoise_auto_encoder(_X, _weights, _biases, _keep_prob):
#定义编码
layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X, _weights['h1']), _biases['b1']))
#dropout
layer_1out = tf.nn.dropout(layer_1, _keep_prob)
#定义中间层
layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1out, _weights['h2']), _biases['b2']))
layer_2out = tf.nn.dropout(layer_2, _keep_prob)
#解码
return tf.nn.sigmoid(tf.matmul(layer_2out, _weights['out']) + _biases['out'])
reconstruction = denoise_auto_encoder(x, weights, biases, dropout_keep_prob)
#cost计算
cost = tf.reduce_mean(tf.pow(reconstruction-y, 2))
#定义优化器
optm = tf.train.AdamOptimizer(0.01).minimize(cost)
加入了dropout的学习参数来定义dropout层
2.设置学习参数,开始训练
#定义训练参数
epochs = 20
batch_size = 256
disp_step = 2
#开始训练
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print ("开始训练")
for epoch in range(epochs):
#获取每批的数量
num_batch = int(mnist.train.num_examples/batch_size)
total_cost = 0.
for i in range(num_batch):
3.生成噪声数据
在这里做了添加噪声的操作,每层取出一批次的数据,将输入数据的每一个像素都加上0.3倍的高斯噪声。
#批次数据
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
#对数据添加噪声
batch_xs_noisy = batch_xs + 0.3*np.random.randn(batch_size, 784)
_, _lost =sess.run(optm, cost, feed_dict= {x: batch_xs_noisy, y: batch_xs, dropout_keep_prob: 1.})
total_cost+=_lost
# 显示训练日志
if epoch % disp_step == 0:
print ("Epoch %02d/%02d average cost: %.6f"
% (epoch, epochs, total_cost/num_batch))
print ("完成")
4.数据可视化
#定义展现数目
show_num = 10
#加了噪声的数据
test_noisy = mnist.test.images[:show_num] + 0.3*np.random.randn(show_num, 784)
#解码器生成的数据
encode_decode = sess.run(reconstruction, feed_dict={x: test_noisy, dropout_keep_prob: 1.})
f, a = plt.subplots(3, 10, figsize=(10, 3))
for i in range(show_num):
#噪声数据,原始数据,生成的数据
a[0][i].imshow(np.reshape(test_noisy[i], (28, 28)))
a[1][i].imshow(np.reshape(mnist.test.images[i], (28, 28)))
a[2][i].matshow(np.reshape(encode_decode[i], (28, 28)), cmap=plt.get_cmap('gray'))
plt.show()
第一行是加入噪声后的图片,第二行是原始图片,第三行为解码的图片。
可以函数,输出的图片还能看出原来的样子,而且将噪声大部分过滤掉了。