1.引入头文件,创建网络模型及定义学习参数变量

对mnist集中的原始输入图片加入噪声,在自编码网络中进行训练,得到抗干扰能力更强的特征提取模型。

引入头文件,创建mnist数据集。

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

2.定义占位符

建立4个网络,每一层都用一个网络来训练,需要训练3个网络,最后再把训练好的各几层组合到一起,形成第4个网络。

n_input = 784
n_hidden_1 = 256
n_hidden_2 = 128
n_classes = 10

#占位符
#第一层输入
x = tf.placeholder(\"float\", [None, n_input])
y = tf.placeholder(\"float\", [None, n_input])
dropout_keep_prob = tf.placeholder(\"float\")
#第二层输入
l2x = tf.placeholder(\"float\", [None, n_hidden_1])
l2y = tf.placeholder(\"float\", [None, n_hidden_1])
#第三层输入
l3x = tf.placeholder(\"float\", [None, n_hidden_2])
l3y = tf.placeholder(\"float\", [None, n_classes])

3定义学习参数

除了输入层,后面的其他三层(256、128、10)每一层都需要单独使用一个自编码网络来训练,所以为这3个网络创建3套学习参数。

#WEIGHTS
weights = {
    #网络1 784-256-784
    \'h1\': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
    \'l1_h2\': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_1])),
    \'l1_out\': tf.Variable(tf.random_normal([n_hidden_1, n_input])),
    #网络2 256-128-256
    \'l2_h1\': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    \'l2_h2\': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_2])),
    \'l2_out\': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_1])),
    #网络3 128-10
    \'out\': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
biases = {
    \'b1\':tf.Variable(tf.zeros([n_hidden_1])),
    \'l1_b2\': tf.Variable(tf.zeros([n_hidden_1])),
    \'l1_out\': tf.Variable(tf.zeros([n_input])),

    \'l2_b1\': tf.Variable(tf.zeros([n_hidden_2])),
    \'l2_b2\': tf.Variable(tf.zeros([n_hidden_2])),
    \'l2_out\': tf.Variable(tf.zeros([n_hidden_1])),

    \'out\': tf.Variable(tf.zeros([n_classes]))
}

4.第一层网络结构

为第一层建立一个自编码网络,并定义其网络结构。这里注意,由于要给第一层加入噪声,所以第一层需要有dropout层。

#第一层的编码输出
l1_out = tf.nn.sigmoid(tf.add(tf.matmul(x, weights[\'h1\']), biases[\'b1\']))

#11解码器MODEL
def noise_l1_autodecoder( _1, _weights, _biases, _keep_prob):
     _1out = tf.nn.dropout( _1, _keep_prob)
     _2 = tf.nn.sigmoid(tf.add(tf.matmul( _1out, _weights[\'l1_h2\']), _biases[\'l1_b2\']))
     _2out = tf.nn.dropout( _2, _keep_prob)
    return tf.nn.sigmoid(tf.matmul( _2out, _weights[\'l1_out\'])+_biases[\'l1_out\'])


#第一层的解码输出
l1_reconstruction = noise_l1_autodecoder(l1_out, weights, biases, dropout_keep_prob)

#计算COST
l1_cost = tf.reduce_mean(tf.pow(l1_reconstruction - y, 2))
#OPTIMIZER
l1_optm = tf.train.AdamOptimizer(0.01).minimize(l1_cost)

5.第二层网络结构

为第二层建立一个自编码网络,并定义其网络结构。

#解码器MODEL
def l2_autodecoder( 1_2, _weights, _biases):
     1_2out = tf.nn.sigmoid(tf.add(tf.matmul( 1_2, _weights[\'l2_h2\']), _biases[\'l2_b2\']))
    return tf.nn.sigmoid(tf.matmul( 1_2out, _weights[\'l2_out\']) + _biases[\'l2_out\'])

#第二层的编码输出
l2_out = tf.nn.sigmoid(tf.add(tf.matmul(l2x, weights[\'l2_h1\']), biases[\'l2_b1\']))
#第二层的解码输出
l2_reconstruction = l2_autodecoder(l2_out, weights, biases)

#COST计算
l2_cost = tf.reduce_mean(tf.pow(l2_reconstruction-l2y, 2))
#优化器
optm2 = tf.train.AdamOptimizer(0.01).minimize(l2_cost)

6.第三层网络结构

为第二层建立一个自编码网络,并定义其网络结构。

l3_out = tf.matmul(l3x, weights[\'out\'])+biases[\'out\']
l3_cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=l3_out, labels=l3y))
l3_optm = tf.train.AdamOptimizer(0.01).minimize(l3_cost)

7.定义级联网络结构

将3层网络连在一起,建立第四个网络,并定义其网络结构。

#3层 级联
#1联2
l1_l2out = tf.nn.sigmoid(tf.add(tf.matmul(l1_out, weights[\'l2_h1\']), biases[\'l2_b1\']))
#2联3
pred = tf.matmul(l1_l2out, weights[\'out\'])+biases[\'out\']
#定义loss和优化器
cost3 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=l3y))
optm3 = tf.train.AdamOptimizer(0.001).minimize(cost3)

8.第一层网络训练

网络结构定义好之后,下面开始第一层网络的训练。

epochs = 50
batch_size = 100
disp_step = 10

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):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            batch_xs_noisy = batch_xs + 0.3*np.random.randn(batch_size,784)
            feeds = {x:batch_xs_noisy,y:batch_xs,dropout_keep_prob:0.5}
            sess.run(l1_optm, feed_dict=feeds)
            total_cost += sess.run(l1_cost, feed_dict=feeds)
            #DISPLAY
        if epoch%disp_step == 0:
            print(\"Epoch %02d/%02d average cost: %.6f\"
                  %(epoch, epochs, total_cost/num_batch))
    print(\"完成  _2 训练\")

执行上面代码,生成如下信息:

开始训练
Epoch 00/50 average cost: 0.113839
Epoch 10/50 average cost: 0.035742
Epoch 20/50 average cost: 0.033140
Epoch 30/50 average cost: 0.032191
Epoch 40/50 average cost: 0.031671
完成  _2 训练

Process finished with exit code 0

从测试数据里面拿出10个样本放到模型里面,将生成的结果可视化。

    show_num = 10
    test_noisy = mnist.test.images[:show_num]+0.3*np.random.randn(show_num, 784)
    encode_decode = sess.run(l1_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()

执行上面代码,生成如下图所示信息:

\"\"

 

收藏 打印