Tensorflow實現softmax Regression識別手寫數字(簡單神經網絡)

# ====================================================
#tensorflow實現softmax Regression識別手寫數字
#
#構造一個簡單的神經網絡不含隱藏層分成四步
#    1.定義算法公式,前向計算
#    2.定義loss函數,選擇優化器,讓優化器優化loss
#    3.迭代對數據訓練
#    4.用測試數據測得準確率
#
#結構的優化
#
# ====================================================
#載入一個tensorflow庫
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape, mnist.validation.labels.shape)
import tensorflow as tf
#創建一個新的InteractiveSession,使用這個命令會將session註冊爲默認的session
sess=tf.InteractiveSession() 


#----------------------------
#前向計算
#----------------------------
#創建一個placeholder,即數據輸入的地方
x=tf.placeholder(tf.float32,[None,784])
#Variable用來存儲模型參數
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
#實現softmax函數
y=tf.nn.softmax(tf.matmul(x,W)+b)
#輸入y_是真實的lable
y_=tf.placeholder(tf.float32,[None,10])


#----------------------------
#定義損失函數cross_entropy
#---------------------------- 
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))#tf.reduce_sum按照reduction_indices指定的軸進行求和

#用封裝好的優化器優化損失函數cross_entropy 
train_step = tf.train.GradientDescentOptimizer(0.8).minimize(cross_entropy)



#----------------------------
#迭代對數據訓練
#----------------------------
#全局參數初始化器
tf.global_variables_initializer().run()

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    train_step.run({x: batch_xs, y_: batch_ys})

#----------------------------
#用測試數據測得準確率
#----------------------------    
#計算分類是否正確
#結果存放在一個布爾型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))#argmax返回一維張量中最大的值所在的位置
#求準確率
#tf.cast將布爾型轉換爲浮點型
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

#準確率
print(accuracy.eval({x:mnist.test.images, y_:mnist.test.labels}))

# #每個批次的大小
# batch_size = 20
# #計算一共有多少個批次
# n_batch = mnist.train.num_examples // batch_size        
# for epoch in range(50):#把所有圖片訓練21次
#     for batch in range(n_batch):#運行幾個批次
#         batch_xs,batch_ys =  mnist.train.next_batch(batch_size)#獲得批次
# #         sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})
#         train_step.run({x: batch_xs, y_: batch_ys})
#         acc = train_step.run(accuracy,feed_dict={x:mnist.test.images,y_:mnist.test.labels})#看準確率的變化
#         print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))    
    

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章