系列文章
前言
深度學習基本上就是處理兩大類問題,分類問題與迴歸問題。系列文章的第4,5篇均是針對迴歸問題進行介紹,本文則會通過簡單的示例,也是經典的tutorial——手寫數字識別的demo來介紹分類任務的模型是如何搭建的。
知識點
mnist數據集,是tensorflow中自帶的教學數據集,數據操作已經寫好了,但是數據需要下載。其中每條數據是的灰度圖。圖片上顯示的各種數字(0-9)的手寫體。
利用這個數據集可以做圖片的10分類將達到識別數字手寫體。
關於mnist數據集相關的操作可以在下文的示例中查看。
tf.nn.softmax()
是對一個向量做softmax的操作。何爲softmax操作即利用如下的計算式對列表中的每一個元素進行計算。
上式中的i代表列表中的具體的數值。
tf.nn.softmax_cross_entropy_with_logits()
這個函數可以求解預測值與真實值的交叉熵,其中參數logits
代表預測的值,labels
代表真實值。
注意計算loss
的時候需要將tf.nn.softmax_cross_entropy_with_logits()
的結果經過tf.reduce_mean()
才能得到最終的平均loss,否則會得到一個列表,包含了一個批次中每一個訓練樣本的loss值。
tf.argmax()
函數的作用是,將張量沿着某一個軸(維度)進行取最大值下標的操作。
tf.argmax([[0.1, 0.3, 0.6],[0.2, 0.5, 0.3]], 1)
>>> [2, 1]
tf.equal(a, b)
函數用於判斷張量a與張量b中哪些元素相等,最終生成一個與a,b相等的張量。a與b相等的位置爲True,其餘位置爲False。
通過tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
可以得到預測正確率的矩陣。
tf.cast()
可以將傳入的張量類型進行轉換(類似於強制類型轉換)。
accuarcy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# tf.cast()把correct_prediction中爲True的轉爲1.0,False轉爲0.0
# 利用 tf.reduce_mean()求平均後就是整個訓練集的正確率
示例
#%% md
# 簡單分類問題
利用mnist數據集實現多選一的分類問題
#%%
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#%% md
載入數據集
#%%
mnist = input_data.read_data_sets("MNIST",one_hot=True)
#%% md
設置batch_size的大小
#%%
batch_size = 50
n_batchs = mnist.train.num_examples // batch_size
#%%
n_batchs
#%% md
## 定義兩個placeholder作爲數據的入口
#%%
x = tf.placeholder(tf.float32, [None, 784],name="x-input")
y = tf.placeholder(tf.float32, [None, 10], name="y-input")
#%%
x,y
#%% md
## 創建隱層網絡
#%%
w = tf.Variable(tf.zeros([784, 10]))
#%%
w
#%%
b = tf.Variable(tf.zeros([1,10]))
#%%
b
#%%
prediction = tf.nn.softmax(tf.matmul(x, w) + b)
#%%
prediction
#%% md
## 創建交叉熵代價函數
#%%
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
#%% md
## 定義優化器
#%%
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
#%%
train_step
#%% md
## 初始化全局變量
#%%
init = tf.global_variables_initializer()
#%% md
## 計算準確率
#%%
correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
accuarcy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#%%
correct_prediction, accuarcy
#%% md
## 訓練
#%%
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
#%%
sess.run(init)
#%%
for epoch in range(200):
for batch in range(n_batchs):
batch_x, batch_y = mnist.train.next_batch(batch_size)
sess.run([train_step],{x:batch_x, y: batch_y})
acc = sess.run(accuarcy, feed_dict = {x:mnist.test.images, y:mnist.test.labels})
print("Iter: ", epoch, "acc: ", acc)
#%%
#%%
#%%