識別數(shù)字在機器學習任務中的地位和 Hello World 在編程中是一樣的豹储。
主要步驟:
- 獲得數(shù)據(jù):from Yann LeCun's website
- 建立模型:softmax
- 定義 tensor约巷,variable:X嗦哆,W,b
- 定義損失函數(shù)驾讲,優(yōu)化器:cross-entropy盈电,gradient descent
- 訓練模型:loop叫编,batch
- 評價:準確率
1. 獲得數(shù)據(jù)
- 來自 Yann LeCun's website:http://yann.lecun.com/exdb/mnist/
- 分為 train,test缨恒,validate谴咸,每個 X 代表一個圖片,y 是它的 label
- 其中圖片由
28*28
像素組成骗露,轉(zhuǎn)化成 array 的形式岭佳,變成1*784
維 - y 變?yōu)?one-h(huán)ot 的形式,即屬于哪個數(shù)字萧锉,就在哪個位置上為 1珊随, 其余為 0
目標:給了 X 后,預測它的 label 是屬于 0~9 類中的哪一類
如果想要看數(shù)據(jù)屬于多類中的哪一類驹暑,首先可以想到用 softmax 來做玫恳。
2. 建立模型
softmax regression 有兩步:
- 把 input 轉(zhuǎn)化為某類的 evidence
- 把 evidence 轉(zhuǎn)化為 probabilities
1. 把 input 轉(zhuǎn)化為某類的 evidence
- 某一類的 evidence 就是像素強度的加權(quán)求和,再加上此類的 bias优俘。
- 如果某個 pixel 可以作為一個 evidence 證明圖片不屬于此類京办,則 weight 為負,否則的話 weight 為正帆焕。
下圖中惭婿,紅色代表負值,藍色代表正值:
2. 把 evidence 轉(zhuǎn)化為 probabilities
簡單看叶雹,softmax 就是把 input 先做指數(shù)财饥,再做一下歸一:
- 歸一的作用:好理解,就是轉(zhuǎn)化成概率的性質(zhì)
- 為什么要取指數(shù):在 《常用激活函數(shù)比較》寫過
http://www.reibang.com/p/22d9720dbf1a- 第一個原因是要模擬 max 的行為折晦,所以要讓大的更大钥星。
- 第二個原因是需要一個可導的函數(shù)。
用圖形表示為:
上面兩步满着,寫成矩陣形式:
模型的代碼只有一行:
y = tf.nn.softmax(tf.matmul(x, W) + b)
3. 定義 tensor 和 variable:
4. 定義損失函數(shù)谦炒,優(yōu)化器:
用 cross-entropy 作為損失來衡量模型的誤差:
其中贯莺,y 是預測, y′ 是實際 .
按照表面的定義宁改,代碼只有一行:
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
不過因為上面不穩(wěn)定缕探,所以實際用:
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
然后用 backpropagation, 且 gradient descent 作為優(yōu)化器还蹲,來訓練模型爹耗,使得 loss 達到最小:
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
5. 訓練模型
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})
6. 評價
看 y 和 y′ 有多少相等的谜喊,轉(zhuǎn)化為準確率潭兽。
再測試一下 test 數(shù)據(jù)集上的準確率,結(jié)果可以達到 92%锅论。
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}))
這只是最簡單的模型讼溺,下次看如何提高精度。
完整代碼和注釋:
溫馨提示最易,用web打開怒坯,代碼格式比較好看
"""A very simple MNIST classifier.
See extensive documentation at
https://www.tensorflow.org/get_started/mnist/beginners
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
FLAGS = None
def main(_):
# Import data
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
# Create the model
x = tf.placeholder(tf.float32, [None, 784])
# a 2-D tensor of floating-point numbers
# None means that a dimension can be of any length
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b
# It only takes one line to define it
# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
# The raw formulation of cross-entropy,
#
# tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),
# reduction_indices=[1]))
# tf.reduce_sum adds the elements in the second dimension of y,
# due to the reduction_indices=[1] parameter.
# tf.reduce_mean computes the mean over all the examples in the batch.
#
# can be numerically unstable.
#
# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw
# outputs of 'y', and then average across the batch.
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# apply your choice of optimization algorithm to modify the variables and reduce the loss.
sess = tf.InteractiveSession()
# launch the model in an InteractiveSession
tf.global_variables_initializer().run()
# create an operation to initialize the variables
# Train~~stochastic training
for _ in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
# Each step of the loop,
# we get a "batch" of one hundred random data points from our training set.
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# Test trained model
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
# use tf.equal to check if our prediction matches the truth
# tf.argmax(y,1) is the label our model thinks is most likely for each input,
# while tf.argmax(y_,1) is the correct label.
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# [True, False, True, True] would become [1,0,1,1] which would become 0.75.
print(sess.run(accuracy, feed_dict={x: mnist.test.images,
y_: mnist.test.labels}))
# ask for our accuracy on our test data,about 92%
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
help='Directory for storing input data')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
學習資料:
https://www.tensorflow.org/get_started/mnist/beginners
今天開始系統(tǒng)學習 TensorFlow藻懒,大家有什么問題可以留言剔猿,一起討論學習。
推薦閱讀 歷史技術(shù)博文鏈接匯總
http://www.reibang.com/p/28f02bb59fe5
也許可以找到你想要的