tensorflow實現(xiàn)softma識別MNIST
識別MNIST已經(jīng)成了深度學習的hello world,所以每次例程基本都會用到這個數(shù)據(jù)集,這個數(shù)據(jù)集在tensorflow內(nèi)部用著很好的封裝,因此可以方便地使用。
這次我們用tensorflow搭建一個softmax多分類器,和之前搭建線性回歸差不多,第一步是通過確定變量建立圖模型,然后確定誤差函數(shù),最后調(diào)用優(yōu)化器優(yōu)化。
誤差函數(shù)與線性回歸不同,這里因為是多分類問題,所以使用了交叉熵。
另外,有一點值得注意的是,這里構(gòu)建模型時我試圖想拆分多個函數(shù),但是后來發(fā)現(xiàn)這樣做難度很大,因為圖是在規(guī)定變量就已經(jīng)定義好的,不能隨意拆分,也不能當做變量傳來傳去,因此需要將他們寫在一起。
代碼如下:
#encoding=utf-8
__author__ = 'freedom'
import tensorflow as tf
def loadMNIST():
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data',one_hot=True)
return mnist
def softmax(mnist,rate=0.01,batchSize=50,epoch=20):
n = 784 # 向量的維度數(shù)目
m = None # 樣本數(shù),這里可以獲取,也可以不獲取
c = 10 # 類別數(shù)目
x = tf.placeholder(tf.float32,[m,n])
y = tf.placeholder(tf.float32,[m,c])
w = tf.Variable(tf.zeros([n,c]))
b = tf.Variable(tf.zeros([c]))
pred= tf.nn.softmax(tf.matmul(x,w)+b)
loss = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1))
opt = tf.train.GradientDescentOptimizer(rate).minimize(loss)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for index in range(epoch):
avgLoss = 0
batchNum = int(mnist.train.num_examples/batchSize)
for batch in range(batchNum):
batch_x,batch_y = mnist.train.next_batch(batchSize)
_,Loss = sess.run([opt,loss],{x:batch_x,y:batch_y})
avgLoss += Loss
avgLoss /= batchNum
print 'every epoch average loss is ',avgLoss
right = tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(right,tf.float32))
print 'Accracy is ',sess.run(accuracy,({x:mnist.test.images,y:mnist.test.labels}))
if __name__ == "__main__":
mnist = loadMNIST()
softmax(mnist)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決pycharm無法刪除invalid interpreter(無效解析器)的問題
這篇文章主要介紹了pycharm無法刪除invalid interpreter(無效解析器)的問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07
Python使用logging實現(xiàn)多進程安全的日志模塊
這篇文章主要為大家詳細介紹了Python如何使用標準庫logging實現(xiàn)多進程安全的日志模塊,文中的示例代碼講解詳細,感興趣的小伙伴可以了解下2024-01-01
CentOS 7下安裝Python 3.5并與Python2.7兼容并存詳解
這篇文章主要給大家介紹了在CentOS 7下安裝Python 3.5并與Python2.7兼容并存的相關(guān)資料,文中將安裝步驟介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面跟著小編來一起學習學習吧。2017-07-07
python腳本調(diào)用iftop 統(tǒng)計業(yè)務(wù)應(yīng)用流量的思路詳解
這篇文章主要介紹了python腳本調(diào)用iftop 統(tǒng)計業(yè)務(wù)應(yīng)用流量的思路詳解,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10

