【TensorFlow篇】--Tensorflow框架实现SoftMax模型识别手写数字集
生活随笔
收集整理的這篇文章主要介紹了
【TensorFlow篇】--Tensorflow框架实现SoftMax模型识别手写数字集
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、前述
本文講述用Tensorflow框架實現(xiàn)SoftMax模型識別手寫數(shù)字集,來實現(xiàn)多分類。
同時對模型的保存和恢復(fù)做下示例。
二、具體原理
代碼一:實現(xiàn)代碼
#!/usr/bin/python # -*- coding: UTF-8 -*- # 文件名: 12_Softmax_regression.pyfrom tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf# mn.SOURCE_URL = "http://yann.lecun.com/exdb/mnist/" my_mnist = input_data.read_data_sets("MNIST_data_bak/", one_hot=True)#從本地路徑加載進來# The MNIST data is split into three parts: # 55,000 data points of training data (mnist.train)#訓(xùn)練集圖片 # 10,000 points of test data (mnist.test), and#測試集圖片 # 5,000 points of validation data (mnist.validation).#驗證集圖片# Each image is 28 pixels by 28 pixels# 輸入的是一堆圖片,None表示不限輸入條數(shù),784表示每張圖片都是一個784個像素值的一維向量 # 所以輸入的矩陣是None乘以784二維矩陣 x = tf.placeholder(dtype=tf.float32, shape=(None, 784)) #x矩陣是m行*784列 # 初始化都是0,二維矩陣784乘以10個W值 #初始值最好不為0 W = tf.Variable(tf.zeros([784, 10]))#W矩陣是784行*10列 b = tf.Variable(tf.zeros([10]))#bias也必須有10個 y = tf.nn.softmax(tf.matmul(x, W) + b)# x*w 即為m行10列的矩陣就是y #預(yù)測值# 訓(xùn)練 # labels是每張圖片都對應(yīng)一個one-hot的10個值的向量 y_ = tf.placeholder(dtype=tf.float32, shape=(None, 10))#真實值 m行10列 # 定義損失函數(shù),交叉熵損失函數(shù) # 對于多分類問題,通常使用交叉熵損失函數(shù) # reduction_indices等價于axis,指明按照每行加,還是按照每列加 cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))#指明按照列加和 一列是一個類別 train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)#將損失函數(shù)梯度下降 #0.5是學(xué)習(xí)率# 初始化變量 sess = tf.InteractiveSession()#初始化Session tf.global_variables_initializer().run()#初始化所有變量 for _ in range(1000):batch_xs, batch_ys = my_mnist.train.next_batch(100)#每次迭代取100行數(shù)據(jù)sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) #每次迭代內(nèi)部就是求梯度,然后更新參數(shù) # 評估# tf.argmax()是一個從tensor中尋找最大值的序號 就是分類號,tf.argmax就是求各個預(yù)測的數(shù)字中概率最大的那一個 correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))# 用tf.cast將之前correct_prediction輸出的bool值轉(zhuǎn)換為float32,再求平均 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))# 測試 print(accuracy.eval({x: my_mnist.test.images, y_: my_mnist.test.labels}))# 總結(jié) # 1,定義算法公式,也就是神經(jīng)網(wǎng)絡(luò)forward時的計算 # 2,定義loss,選定優(yōu)化器,并指定優(yōu)化器優(yōu)化loss # 3,迭代地對數(shù)據(jù)進行訓(xùn)練 # 4,在測試集或驗證集上對準確率進行評測代碼二:保存模型
# 有時候需要把模型保持起來,有時候需要做一些checkpoint在訓(xùn)練中 # 以致于如果計算機宕機,我們還可以從之前checkpoint的位置去繼續(xù) # TensorFlow使得我們?nèi)ケ4婧图虞d模型非常方便,僅需要去創(chuàng)建Saver節(jié)點在構(gòu)建階段最后 # 然后在計算階段去調(diào)用save()方法from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf # mn.SOURCE_URL = "http://yann.lecun.com/exdb/mnist/" my_mnist = input_data.read_data_sets("MNIST_data_bak/", one_hot=True)# The MNIST data is split into three parts: # 55,000 data points of training data (mnist.train) # 10,000 points of test data (mnist.test), and # 5,000 points of validation data (mnist.validation).# Each image is 28 pixels by 28 pixels# 輸入的是一堆圖片,None表示不限輸入條數(shù),784表示每張圖片都是一個784個像素值的一維向量 # 所以輸入的矩陣是None乘以784二維矩陣 x = tf.placeholder(dtype=tf.float32, shape=(None, 784)) # 初始化都是0,二維矩陣784乘以10個W值 W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10]))y = tf.nn.softmax(tf.matmul(x, W) + b)# 訓(xùn)練 # labels是每張圖片都對應(yīng)一個one-hot的10個值的向量 y_ = tf.placeholder(dtype=tf.float32, shape=(None, 10)) # 定義損失函數(shù),交叉熵損失函數(shù) # 對于多分類問題,通常使用交叉熵損失函數(shù) # reduction_indices等價于axis,指明按照每行加,還是按照每列加 cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)# 初始化變量 init = tf.global_variables_initializer() # 創(chuàng)建Saver()節(jié)點 saver = tf.train.Saver()#在運算之前,初始化之后 n_epoch = 1000with tf.Session() as sess:sess.run(init)for epoch in range(n_epoch):if epoch % 100 == 0:save_path = saver.save(sess, "./my_model.ckpt")#每跑100次save一次模型,可以保證容錯性#直接保存session即可。 batch_xs, batch_ys = my_mnist.train.next_batch(100)#每一批次跑的數(shù)據(jù) 用m行數(shù)據(jù)/迭代次數(shù)來計算出來。sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})best_theta = W.eval()save_path = saver.save(sess, "./my_model_final.ckpt")#保存最后的模型,session實際上保存的上面所有的數(shù)據(jù)代碼三:恢復(fù)模型
from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf # mn.SOURCE_URL = "http://yann.lecun.com/exdb/mnist/" my_mnist = input_data.read_data_sets("MNIST_data_bak/", one_hot=True)# The MNIST data is split into three parts: # 55,000 data points of training data (mnist.train) # 10,000 points of test data (mnist.test), and # 5,000 points of validation data (mnist.validation).# Each image is 28 pixels by 28 pixels# 輸入的是一堆圖片,None表示不限輸入條數(shù),784表示每張圖片都是一個784個像素值的一維向量 # 所以輸入的矩陣是None乘以784二維矩陣 x = tf.placeholder(dtype=tf.float32, shape=(None, 784)) # 初始化都是0,二維矩陣784乘以10個W值 W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10]))y = tf.nn.softmax(tf.matmul(x, W) + b) # labels是每張圖片都對應(yīng)一個one-hot的10個值的向量 y_ = tf.placeholder(dtype=tf.float32, shape=(None, 10))saver = tf.train.Saver()with tf.Session() as sess: saver.restore(sess, "./my_model_final.ckpt")#把路徑下面所有的session的數(shù)據(jù)加載進來 y y_head還有模型都保存下來了。# 評估# tf.argmax()是一個從tensor中尋找最大值的序號,tf.argmax就是求各個預(yù)測的數(shù)字中概率最大的那一個correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))# 用tf.cast將之前correct_prediction輸出的bool值轉(zhuǎn)換為float32,再求平均accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))# 測試print(accuracy.eval({x: my_mnist.test.images, y_: my_mnist.test.labels}))轉(zhuǎn)載于:https://www.cnblogs.com/LHWorldBlog/p/8661434.html
總結(jié)
以上是生活随笔為你收集整理的【TensorFlow篇】--Tensorflow框架实现SoftMax模型识别手写数字集的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VLFeat中SIFT特征点检测
- 下一篇: Java 并发工具箱之concurren