前言:
本文主要針對圖片格式的數字進行識別處理、建模和識別,在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}))