tensorflow 神經網路基礎
首先介紹本文使用的資料集MNIST手寫數字資料集:
MNIST資料集的官網是http://yann.lecun.com/exdb/mnist/
是由Google實驗室的Corinna Cortes和紐約大學柯朗研究所的YannLeCun建有一個手寫數字資料庫,訓練庫有60,000張手寫數字影象,測試庫有10,000張。
可以手動在官網下載,也可以在python中進行下載
在這裡,我們提供了一份python原始碼用於自動下載和安裝這個資料集。你可以下載這份程式碼,然後用下面的程式碼匯入到你的專案裡面,也可以直接複製貼上到你的程式碼檔案裡面。
From tensorflow.examples.tutorials.mnist importinput_data mnist =input_data.read_data_sets("MNIST_data/", one_hot=True)
MNIST資料庫會直接下載在專案的根目錄下
然後進行機器學習,我將機器學習分為以下幾個步驟:
Step1:匯入資料
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
匯入的MNIST資料集,如果本地中包含則直接匯入,如果沒有則會通過官網進行下載,資料集中的資料可以進行編碼打印出來,具體的實現步驟可以在網上尋找具體的程式碼。
Step2:設定引數
x = tf.placeholder(tf.float32, [None,784]) 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])
tf.placeholder代表佔位符,具體指輸入的影象和輸入的標籤
w代表權值矩陣
b代表偏執矩陣
softmax我理解為是啟用函式
y代表預測的輸出
Step3:設定損失函式
cross_entropy =tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y))) train_sept = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
根據y,y_通過交叉熵構建損失函式,並用學習率0.01的梯度下降演算法使得損失函式值最小
Step4:建立session,初始化所有變數
sess = tf.InteractiveSession() tf.global_variables_initializer().run()
Step5:優化引數
for i in range(1000): batch_xs, batch_ys =mnist.train.next_batch(100) sess.run(train_sept, feed_dict={x:batch_xs, y_: batch_ys})
優化權值矩陣和偏置,也就是講的訓練過程
Step6:檢測測試集
corrent_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(corrent_prediction, tf.float32)) print/
(sess.run(accuracy,feed_dict{x:mnist.test.images,y_:mnist.test.labels}))
在測試集中檢測準確率
最終結果:
測試集中準確率0.9046: