初识Tensorflow 数字识别MNIST

时间:2021-09-22 20:00:05

整体流程:
1.定义算法公式
2.定义loss 选定优化器,并制定优化器优化loss
3.迭代数据进行训练
4.在测试集或验证集上对准确率进行测评

首先导入tensorflow 与mnist的input-data 用来获取traning test 包

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

将训练及测试图集保存在项目中的 MNIST_data目录下,没有时会自动联网下载保存

mnist = input_data.read_data_sets('./MNIST_data', one_hot=True)

注册默认的tensorflow会话

sess = tf.InteractiveSession()

定义输入x 为placeholder占位符

x = tf.placeholder(tf.float32, [None, 784])

定义 权重 W 偏置值b

W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

定义y的计算函数 用sotfmax Regression算法
y = softmax(Wx + b)

y = tf.nn.softmax(tf.matmul(x, W) + b)

定义损失函数cross_entropy
cross_entropy 通常用来处理分类问题

y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

定义优化算法

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

初始化所有变量

sess.run(tf.global_variables_initializer())

迭代 train_step 算法 将batch_xs batch_ys feed给占位符 x y_

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

检验是否正确的预测

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))

预测准确率

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy,feed_dict={x:mnist.test.images,y_:mnist.test.labels}))

完整代码如下:

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

mnist = input_data.read_data_sets('./MNIST_data', one_hot=True)

# 注册默认的tensorflow会话
sess = tf.InteractiveSession()

# 输入x placeholder为占位符
x = tf.placeholder(tf.float32, [None, 784])

# 权重 W 偏置值b
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

# 定义y的计算函数 用sotfmax Regression算法
# y = softmax(Wx + b)
y = tf.nn.softmax(tf.matmul(x, W) + b)

#定义损失函数cross_entropy
#cross_entropy 通常用来处理分类问题

y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

# 定义优化算法
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

# 初始化所有变量
sess.run(tf.global_variables_initializer())

# 迭代 train_step 算法 将batch_xs batch_ys feed给占位符 x y_
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

# 是否正确的预测

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))

# 预测准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

print(sess.run(accuracy,feed_dict={x:mnist.test.images,y_:mnist.test.labels}))

总结:

Tensorflow中定义的每个公式的计算其实并没有立刻发生,只有等调用run方法并feed数据时计算才会真正的执行。
例如代码中的corss_entropy、train_step、accuracy等都是计算图中的节点,通过run方法执行这些节点来获取结果`