Tensorflow下运行数字识别

来源:互联网 发布:怎么在淘宝上投诉卖家 编辑:程序博客网 时间:2024/06/04 00:24

前言:
本文主要针对图片格式的数字进行识别处理、建模和识别,在tensorflow集群下运行。

代码:

-- coding: utf-8 --

“””
Spyder Editor

This is a temporasry script file.
MNIST TEST
Written by zhouguoxin on 2017-12-22
“”“

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(“C:/Users/zhou8/.spyder-py3/MNIST_data”,one_hot=True)

import tensorflow as tf

输入图像数据占位符

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

计算权值和偏差

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

使用softmax模型

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

代价函数占位符

y_ = tf.placeholder(tf.float32,[None,10])

计算交叉熵评估代价

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

使用梯度下降算法优化:学习型速率为0.5

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

build Session

sess = tf.InteractiveSession()

初始化变量

tf.global_variables_initializer().run()

训练模型,训练1000次

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

calculate

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}))

原创粉丝点击