TensorFlow學習筆記(1):使用softmax對手寫體數字(MNIST資料集)進行識別
使用softmax實現手寫體數字識別完整程式碼如下:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print("Download Done!")
x = tf.placeholder(tf.float32, [None, 784])
# paras
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10 ]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])
# loss func
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# init
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
# train
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.arg_max(y, 1), tf.arg_max(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})
在實現過程中主要遇到的幾個坑
讀入MNIST時存在的問題: 存在網路限制,可能有些國外的資料網站不能訪問或者訪問速度較慢,執行讀取MNIST資料庫的時候,會出現長時間沒有反應但是沒有報錯的情況,可能是直接使用程式碼下載MNIST資料庫的速度較慢。
解決方案: 直接從MNIST資料集官方網站 Yann LeCun’s website 下載資料庫,並直接將下載好的4個
.gz
檔案放置到當前目錄的MNIST_data/
資料夾裡面,不需要解壓。
MNIST_data/
資料夾是由語句mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
確定,目錄的名字可以更改。讀入input_data語句存在的問題:
原來文件中的程式碼是:import tensorflow.examples.tutorials.mnist.input_data
mnist = input_data.read_data_sets(“MNIST_data/”, one_hot=True)可能還附帶一個
input_data.py
檔案,這樣使用的話會報錯。
在最新的官方文件中,直接使用如下程式碼:from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(“MNIST_data/”, one_hot=True)不需要再匯入
input_data.py
檔案TensorFlow中變數Variable 和 佔位符placeholder的使用技巧
就我目前觀察到的來講,Variable主要用來定義大小未確定,會隨著程式而改變的tensor,variable可以在程式中途進行feed賦值。
variable在使用之前都要進行初始化,可以使用語句sess.run(tf.initialize_all_variables())
或者sess.run(tf.global_variables_initializer())
,推薦使用後一種初始化方式。