識(shí)別數(shù)字在機(jī)器學(xué)習(xí)任務(wù)中的地位和 Hello World 在編程中是一樣的。
主要步驟:
- 獲得數(shù)據(jù):from Yann LeCun's website
- 建立模型:softmax
- 定義 tensor,variable:X,W,b
- 定義損失函數(shù),優(yōu)化器:cross-entropy,gradient descent
- 訓(xùn)練模型:loop,batch
- 評(píng)價(jià):準(zhǔn)確率
1. 獲得數(shù)據(jù)
- 來(lái)自 Yann LeCun's website:http://yann.lecun.com/exdb/mnist/
- 分為 train,test,validate,每個(gè) X 代表一個(gè)圖片,y 是它的 label
- 其中圖片由
28*28像素組成,轉(zhuǎn)化成 array 的形式,變成1*784維 - y 變?yōu)?one-h(huán)ot 的形式,即屬于哪個(gè)數(shù)字,就在哪個(gè)位置上為 1, 其余為 0

目標(biāo):給了 X 后,預(yù)測(cè)它的 label 是屬于 0~9 類(lèi)中的哪一類(lèi)

如果想要看數(shù)據(jù)屬于多類(lèi)中的哪一類(lèi),首先可以想到用 softmax 來(lái)做。
2. 建立模型
softmax regression 有兩步:
- 把 input 轉(zhuǎn)化為某類(lèi)的 evidence
- 把 evidence 轉(zhuǎn)化為 probabilities
1. 把 input 轉(zhuǎn)化為某類(lèi)的 evidence

- 某一類(lèi)的 evidence 就是像素強(qiáng)度的加權(quán)求和,再加上此類(lèi)的 bias。
- 如果某個(gè) pixel 可以作為一個(gè) evidence 證明圖片不屬于此類(lèi),則 weight 為負(fù),否則的話 weight 為正。
下圖中,紅色代表負(fù)值,藍(lán)色代表正值:

2. 把 evidence 轉(zhuǎn)化為 probabilities

簡(jiǎn)單看,softmax 就是把 input 先做指數(shù),再做一下歸一:

- 歸一的作用:好理解,就是轉(zhuǎn)化成概率的性質(zhì)
- 為什么要取指數(shù):在 《常用激活函數(shù)比較》寫(xiě)過(guò)
http://www.itdecent.cn/p/22d9720dbf1a- 第一個(gè)原因是要模擬 max 的行為,所以要讓大的更大。
- 第二個(gè)原因是需要一個(gè)可導(dǎo)的函數(shù)。
用圖形表示為:


上面兩步,寫(xiě)成矩陣形式:

模型的代碼只有一行:
y = tf.nn.softmax(tf.matmul(x, W) + b)
3. 定義 tensor 和 variable:

4. 定義損失函數(shù),優(yōu)化器:
用 cross-entropy 作為損失來(lái)衡量模型的誤差:

其中,y 是預(yù)測(cè), y′ 是實(shí)際 .
按照表面的定義,代碼只有一行:
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
不過(guò)因?yàn)樯厦娌环€(wěn)定,所以實(shí)際用:
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
然后用 backpropagation, 且 gradient descent 作為優(yōu)化器,來(lái)訓(xùn)練模型,使得 loss 達(dá)到最小:
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
5. 訓(xùn)練模型
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. 評(píng)價(jià)
看 y 和 y′ 有多少相等的,轉(zhuǎn)化為準(zhǔn)確率。
再測(cè)試一下 test 數(shù)據(jù)集上的準(zhǔn)確率,結(jié)果可以達(dá)到 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}))
這只是最簡(jiǎn)單的模型,下次看如何提高精度。
完整代碼和注釋:
溫馨提示,用web打開(kāi),代碼格式比較好看
"""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)
學(xué)習(xí)資料:
https://www.tensorflow.org/get_started/mnist/beginners
今天開(kāi)始系統(tǒng)學(xué)習(xí) TensorFlow,大家有什么問(wèn)題可以留言,一起討論學(xué)習(xí)。
推薦閱讀 歷史技術(shù)博文鏈接匯總
http://www.itdecent.cn/p/28f02bb59fe5
也許可以找到你想要的