Tensorflow study notes-handwritten digit recognition

Use the tensorflow framework to build a fully connected neural network for recognizing handwritten numbers. I hope it will be helpful to everyone.
Insert picture description here

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

# 获取数据集
# one_hot设置为True,将标签数据转化为0/1,如[1,0,0,0,0,0,0,0,0,0]
mnist=input_data.read_data_sets('MNIST_data',one_hot=True)

# 定义一个批次的大小
batch_size=100
n_batch=mnist.train.num_examples//batch_size

# 定义两个placeholder
# 行数值为None,None可以取任意数,本例中将取值100,即取决于pitch_size
# 列数值为784,因为输入图像尺寸已由28*28转换为1*784
x=tf.placeholder(tf.float32,[None,784])
y=tf.placeholder(tf.float32,[None,10])

# 定义两个变量
w=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))

# 定义一个神经网络
# softmax的作用是将tf.matmul(x,w)+b的结果转换为概率值,举例如下:
# [9,2,1,1,2,1,1,2,1,1]
# [0.99527,0.00091,0.00033,0.00033,0.00091,0.00033,0.00033,0.00091,0.00033,0.00033]
prediction=tf.nn.softmax(tf.matmul(x,w)+b)

# 定义损失函数
loss=tf.reduce_mean(tf.square(y-prediction))

# 定义优化器
optimizer=tf.train.GradientDescentOptimizer(0.2)

# 定义模型,优化器通过调整loss里的参数,使loss不断减小
train=optimizer.minimize(loss)

# 统计准确率
# tf.argmax返回第一个参数中最大值的下标
# tf.equal比较两个参数是否相等,返回True或False
correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
# tf.cast将布尔类型转换为浮点类型
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

with tf.Session() as sess:
	sess.run(tf.global_variables_initializer())
	# epoch为周期数,所有批次训练完为一个周期
	for epoch in range(20):
		for batch in range(n_batch):
			# 每次取出batch_size条数据进行训练
			batch_xs,batch_ys=mnist.train.next_batch(batch_size)
			sess.run(train,feed_dict={
    
    x:batch_xs,y:batch_ys})
		acc = sess.run(accuracy,feed_dict={
    
    x:mnist.test.images,y:mnist.test.labels})
		print('epoch=',epoch,' ','acc=',acc)

Version information:
OS: Win7 64-bit or Win10 64-bit
python: 3.6.x
tensorboard: 1.6.0
tensorflow: 1.4.0
tensorflow-tensorboard: 0.4.0
Remarks: tensorflow-tensorboard0.4.0 is automatically installed when tensorflow 1.4.0 is installed
## ############################################## #
After decompressing the MNIST_data file and putting it in the same folder as the Python file, it can be used. The MNIST_data file download link:
link: https://pan.baidu.com/s/1k65qXdFhmy_9SBlrBQ9H5A
extraction code: 81im
######## ###########################################

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/wxsy024680/article/details/114506035