0
点赞
收藏
分享

微信扫一扫

python深度学习库tensorflow——实现FC卷积神经网络识别mnist手写体


全栈工程师开发手册 (作者:栾鹏)

​​python教程全解​​

tensorflow编程的一个基本步骤:

1、定义数据
2、定义计算图与变量
3、定义会话
4、进行计算

代码会自动在当前目录生成MNIST_data文件夹,并下载

t10k-images-idx3-ubyte.gz
t10k-labels-idx1-ubyte.gz
train-images-idx3-ubyte.gz
train-labels-idx1-ubyte.gz

# 定义数据
# 定义计算图与变量
# 定义会话
# 进行计算

# tensorflow建立全连接网络模型预测mnist数据

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#加载mnist数据集
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
# 1.定义数据。在神经网络里我们需要定义的数据就是输入训练/测试数据,而变量用来存储网络模型里的各种参数。
x = tf.placeholder( tf.float32, [None, 784] )
y_ = tf.placeholder( tf.float32, [None, 10] )
# 2.定义计算图与变量。对于神经网络来说,涉及到的操作主要有三部分:网络模型定义,损失函数定义、训练/优化方法定义。
W = tf.Variable( tf.zeros([784,10]) ) #w为784*10的矩阵,输入层为784个像素点
b = tf.Variable( tf.zeros([10]) ) #输出为10,偏离值也为10
# 计算函数定义
y = tf.nn.softmax( tf.matmul(x,W) + b )
# 损失函数定义(交叉熵代价函数)
cross_entropy = tf.reduce_mean( -tf.reduce_sum(y_*tf.log(y), reduction_indices=[1] ) ) # reduce_sum内第一个参数为交叉熵公式
# 训练/优化方法定义。神经网络常采用SGD(Stochastic Gradient Descent)进行网络的优化训练。tensorflow会自动根据前面定义的计算图进行forward和backward计算并更新参数。
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# 3.定义会话
session = tf.InteractiveSession()
tf.global_variables_initializer().run()
# 4.进行计算。对于神经网络来说,就是要开始迭代进行训练和评估,降低损失函数。
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
train_step.run( {x:batch_xs, y_:batch_ys} )
print(i)


# 交叉验证,评估模型
correct_prediction = tf.equal( tf.argmax(y,1), tf.argmax(y_,1) )
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32) )
print(accuracy.eval({x:mnist.test.images, y_:mnist.test.labels} ))

输出成功率约为91%


举报

相关推荐

0 条评论