实例76:提取图片的特征,并利用特征还原图片

通过构建一个两层降维的自编码网络,将MNIST数据集的数据特征提取出来,并通过这些特征再重建一个MNIST数据集

1.引入头文件,并加载MNIST数据

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt 

#导入MINST数据集
from tensorflow.examples.tutorials.mnist import input_data
minst = input_data.read_data_sets("   data/", one_hot=True)

3.定义网络模型

下面输入MNIST数据集的图片,将其像素点组成的数据(28×28=784)从784维降到256,然后降到128,最后再以同样的方式经过128再经过256,最后还原到原来图片。

learning_rate = 0.01
n_hidden_1 = 256
n_hidden_2 = 128
n_input = 784

#占位符
x = tf.placeholder("float", [None, n_input])    #输入
y = x                                           #输出

#学习参数
weights = {
    'encoder_h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
    'encoder_h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    'decoder_h1': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_1])),
    'decoder_h2': tf.Variable(tf.random_normal([n_hidden_1, n_input])),
}
biases = {
    'encoder_b1': tf.Variable(tf.zeros([n_hidden_1])),
    'encoder_b2': tf.Variable(tf.zeros([n_hidden_2])),
    'decoder_b1': tf.Variable(tf.zeros([n_hidden_1])),
    'decoder_b2': tf.Variable(tf.zeros([n_input])),
}


# 编码
def encoder(x):
    layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['encoder_h1']),biases['encoder_b1']))
    layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['encoder_h2']), biases['encoder_b2']))
    return layer_2


# 解码
def decoder(x):
    layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['decoder_h1']),biases['decoder_b1']))
    layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['decoder_h2']),biases['decoder_b2']))
    return layer_2

#输出的节点
encoder_out = encoder(x)
pred = decoder(encoder_out)

# 使用平方差为cost
cost = tf.reduce_mean(tf.pow(y - pred, 2))
optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)

由于输出标签也是输入标签,所以直接定义为y=x

3.开始训练

设置训练参数,一次取256条数据,将所有训练数据集进行20次的迭代训练

#训练参数
training_epochs = 20 
batch_size = 256
display_step = 5

#启动会话
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    total_batch = int(mnist.train.num_examples/batch_size)
    
    for epoch in range(training_epochs):
        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs})
        
         if epoch % display_step == 0:# 现实日志信息
            print("Epoch:", '%04d' % (epoch+1),"cost=", "{:.9f}".format(c))

    print("完成!")

4.测试模型

通过MNIST数据集中的test集来测试一下模型的准确度

  	corrent_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(corrent_prediction, "float"))
    print("Accuracy:", 1-accuracy.eval({x:mnist.test.images, y:mnist.test.images}))

5.双比输入和输出

随意取出10张图片,对比一些输入和输出,可以看到自编码网络还原的图片与真实的图片几乎一样。

 #可视化结果
    show_num = 10
    reconstruction = sess.run(pred, feed_dict={x:mnist.test.images[:show_num]})
    f, a = plt.subplots(2, 10, figsize=(10,2))
    for i in range(show_num):
        a[0][i].imshow(np.reshape(mnist.test.images[i], (28, 28)))
        a[1][i].imshow(np.reshape(reconstruction[i], (28, 28)))
    plt.draw()

执行上面的代码会生成下面的图片
在这里插入图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值