TensorFlow MNIST TensorBoard版本
生活随笔
收集整理的這篇文章主要介紹了
TensorFlow MNIST TensorBoard版本
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼?
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_datasess = tf.InteractiveSession()#遠程下載MNIST數據,建議先下載好并保存在MNIST_data目錄下 def DownloadData():mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) #編碼格式:one-hotprint(mnist.train.images.shape, mnist.train.labels.shape) #訓練數據55000條print(mnist.test.images.shape, mnist.test.labels.shape) #測試數據10000條print(mnist.validation.images.shape, mnist.validation.labels.shape) #驗證數據5000條return mnistdef Train(mnist):#Step1 定義算法公式Softmax Regressionx = tf.placeholder(tf.float32, shape=(None, 784)) #構建占位符,代表輸入的圖像,維度None表示樣本的數量可以是任意的,維度784代表特征向量,由圖像大小28*28轉換而來weights = tf.Variable(tf.zeros([784, 10])) #構建一個變量,代表訓練目標weights,初始化為0biases = tf.Variable(tf.zeros([10])) #構建一個變量,代表訓練目標biases,初始化為0y = tf.nn.softmax(tf.matmul(x, weights) + biases) #構建了一個softmax的模型:y = softmax(Wx + b),y指樣本的預測值y_ = tf.placeholder(tf.float32, [None, 10]) # 構建占位符,代表樣本標簽的真實值tf.summary.histogram("/weights", weights)#Step2 定義損失函數,選定優化器,并指定優化器優化損失函數# 定義交叉熵損失函數cross_entropy = tf.reduce_mean( -tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]) )tf.summary.scalar('cross_entropy', cross_entropy)# 使用梯度下降算法(學習率為0.5)來最小化這個交叉熵損失函數train = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)merged = tf.summary.merge_all()writer = tf.summary.FileWriter("output/", sess.graph)#Step3 訓練數據tf.global_variables_initializer().run()for i in range(2001): #迭代次數batch_x, batch_y = mnist.train.next_batch(100) #一個batch的大小為100, 使用一個batch的數據來訓練模型sess.run(train, feed_dict={x: batch_x, y_: batch_y}) #用訓練數據替代占位符來執行訓練if (i % 100 == 0):print("i=%d, 準確率=%g" % (i, Test(mnist, weights, biases)) )result = sess.run(merged, feed_dict={x: batch_x, y_: batch_y})writer.add_summary(result, i)print("準確率=%g" % Test(mnist, weights, biases))# 在測試數據上對準確率進行評測 def Test(mnist, weights, biases):x = tf.placeholder(tf.float32, [None, 784]) #測試數據y = tf.nn.softmax(tf.matmul(x, weights) + biases) #預測值y_ = tf.placeholder(tf.float32, [None, 10]) #真實值# tf.argmax()返回的是某一維度上其數據最大所在的索引值,在這里即代表預測值和真實值# 判斷預測值y和真實值y_中最大數的索引是否一致,y的值為1-10概率correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # 用平均值來統計測試準確率return sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}) # 打印測試信息def main():mnist = DownloadData()Train(mnist)if __name__ == '__main__':main()運行TensorBoard
總結
以上是生活随笔為你收集整理的TensorFlow MNIST TensorBoard版本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TensorFlow交叉熵
- 下一篇: 2017年最流行的15个数据科学Pyth