數字識別
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#讀取數據集
mnist = input_data.read_data_sets("MNIST_data/",one_hot = True)
#設置訓練數據 x,連接權重 W 和偏置 b
x = tf.placeholder("float",[None,784])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
#對 x 和 W 進行內積運算後把結果傳遞給 softmax 函數,計算輸出 y
y = tf.nn.softmax(tf.matmul(x,W)+b)
#設置期望輸出 y
y_ = tf.placeholder("float",[None,10])
#計算交叉熵
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
#使用梯度下降最小化交叉熵
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
#初始化
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
#迭代訓練
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,"float"))
print(sess.run(accuracy,feed_dict = {x:mnist.test.images,y_:mnist.test.labels}))
運行之後的分類準確率在91%左右