# 导入模块
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("E:\\MNIST_data\\", one_hot=True) #模型训练
# 设置超参数
learning_rate = 0.01 # 学习率
training_epochs = 20 # 训练轮数
batch_size = 256 # 每次训练的数据
display_step = 1 # 每隔多少轮显示一次训练结果
examples_to_show = 10 # 提示从测试集中选择10张图片取验证自动编码器的结果 # 网络参数
n_hidden_1 = 256 # 第一个隐藏层神经元个数(特征值格式)
n_hidden_2 = 128 # 第二个隐藏层神经元格式
n_input = 784 # 输入数据的特征个数 28*28=784 # 定义输入数据,无监督不需要标注数据,所以只有输入图片
X = tf.placeholder("float", [None, n_input]) #初始化每一层的权重和偏置
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.random_normal([n_hidden_1])),
'encoder_b2': tf.Variable(tf.random_normal([n_hidden_2])),
'decoder_b1': tf.Variable(tf.random_normal([n_hidden_1])),
'decoder_b2': tf.Variable(tf.random_normal([n_input])),
} #定义自动编码模型的网络结构,包括压缩和解压的过程 # 定义压缩函数
def encoder(x):
# Encoder Hidden layer with sigmoid activation #1
layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['encoder_h1']),biases['encoder_b1']))
# Decoder Hidden layer with sigmoid activation #2
layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['encoder_h2']),biases['encoder_b2']))
return layer_2 # 定义解压函数
def decoder(x):
# Encoder Hidden layer with sigmoid activation #1
layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['decoder_h1']),biases['decoder_b1']))
# Decoder Hidden layer with sigmoid activation #2
layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['decoder_h2']),biases['decoder_b2']))
return layer_2 # 建立模型
encoder_op = encoder(X)
decoder_op = decoder(encoder_op) # 得出预测分类值
y_pred = decoder_op
# 得出真实值,即输入值
y_true = X # 定义损失函数和优化器
cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2))
optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost) # 初始化变量
init = tf.global_variables_initializer() # 3 训练数据及评估模型
with tf.Session() as sess:
sess.run(init)
total_batch = int(mnist.train.num_examples/batch_size)
# 开始训练
for epoch in range(training_epochs):
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Run optimization op (backprop) and cost op (to get loss value)
_, 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("Optimization Finished!") # 对测试集应用训练好的自动编码网络
encode_decode = sess.run(
y_pred, feed_dict={X: mnist.test.images[:examples_to_show]})
# 比较测试集原始图片和自动编码网络的重建结果
f, a = plt.subplots(2, 10, figsize=(10, 2))
for i in range(examples_to_show):
a[0][i].imshow(np.reshape(mnist.test.images[i], (28, 28)))
a[1][i].imshow(np.reshape(encode_decode[i], (28, 28)))
f.show()
plt.draw()
#plt.waitforbuttonpress()

吴裕雄 PYTHON 神经网络——TENSORFLOW 无监督学习处理MNIST手写数字数据集的更多相关文章

  1. 吴裕雄 python 神经网络TensorFlow实现LeNet模型处理手写数字识别MNIST数据集

    import tensorflow as tf tf.reset_default_graph() # 配置神经网络的参数 INPUT_NODE = 784 OUTPUT_NODE = 10 IMAGE ...

  2. 吴裕雄 python 神经网络——TensorFlow实现AlexNet模型处理手写数字识别MNIST数据集

    import tensorflow as tf # 输入数据 from tensorflow.examples.tutorials.mnist import input_data mnist = in ...

  3. 吴裕雄 python 神经网络——TensorFlow 循环神经网络处理MNIST手写数字数据集

    #加载TF并导入数据集 import tensorflow as tf from tensorflow.contrib import rnn from tensorflow.examples.tuto ...

  4. 吴裕雄 python 神经网络——TensorFlow 使用卷积神经网络训练和预测MNIST手写数据集

    import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_dat ...

  5. 吴裕雄 python 神经网络——TensorFlow 训练过程的可视化 TensorBoard的应用

    #训练过程的可视化 ,TensorBoard的应用 #导入模块并下载数据集 import tensorflow as tf from tensorflow.examples.tutorials.mni ...

  6. 吴裕雄 python 神经网络——TensorFlow实现搭建基础神经网络

    import numpy as np import tensorflow as tf import matplotlib.pyplot as plt def add_layer(inputs, in_ ...

  7. 吴裕雄 python 神经网络——TensorFlow图片预处理调整图片

    import numpy as np import tensorflow as tf import matplotlib.pyplot as plt def distort_color(image, ...

  8. 吴裕雄 python 神经网络——TensorFlow pb文件保存方法

    import tensorflow as tf from tensorflow.python.framework import graph_util v1 = tf.Variable(tf.const ...

  9. 吴裕雄 python 神经网络——TensorFlow 数据集高层操作

    import tempfile import tensorflow as tf train_files = tf.train.match_filenames_once("E:\\output ...

随机推荐

  1. Manacher算法求最长回文串模板

    #include <algorithm> #include <iostream> #include <cstring> #include <cstdio> ...

  2. vue老项目升级vue-cli3.0

    第一步我们卸载全局的vue2.0然后: 打开命令行 输入npm install -g @vue/cli-init   这个就是会安装全局的vue3.0版本.安装好之后我们也可以vue -V查看当前vu ...

  3. Tomcat 加载外部dll时如何配置

    1.在myeclipse环境下配置 先将dll放置在c:\windows\system32中,然后在myEclipse中,window->Preferences->MyEclipse-&g ...

  4. 在MyEclipse中修改文件名出现问题

    问题描述:An exception has been caught while processing the refactoring 'Rename Compilation Unit'. 问题原因:项 ...

  5. 《CSS揭秘》》

    1,透明边框 默认状态下,背景会延伸到边框区域的下层.这样就在半透明的黑色边框中透出了这个容器自己的纯白色背景. 谢天谢地,从w3c的背景与边框第三版开始,我们可以通过 background-clip ...

  6. 解决windows配置visual studio code调试golang环境问题

    写这篇随笔是为了Mark下在这个过程中配到的几个问题 1.具体过程可参考https://www.cnblogs.com/JerryNo1/p/5412864.html,Jerry博主写的非常详细了 1 ...

  7. AcWing 790. 数的三次方根

    #include<bits/stdc++.h> using namespace std ; int main(){ double x; cin>>x; ,r=; ) { ; i ...

  8. testng如何实现用例间依赖

    todo: 参考: https://www.cnblogs.com/znicy/p/6534893.html

  9. MongoDB 在Windows环境的下载、安装、配置

    MongoDB4.0在Windows环境的下载.安装.配置 今天本想玩玩MongoDB,可因工作机上未下载Linux虚拟机,下载多耗时.无奈只能先下载Windows版本耍耍.不料,Windows在安装 ...

  10. js的变量(01)

    变量的声明用的修饰符 var ,let ,const var是普通变量      var   变量名  = 变量值         可以重复定义可以多次修改 let是es6新加的语法   let 变量 ...