TensorFlow MNIST (Softmax)
生活随笔
收集整理的這篇文章主要介紹了
TensorFlow MNIST (Softmax)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
代碼
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_datasess = tf.InteractiveSession()#遠(yuǎn)程下載MNIST數(shù)據(jù),建議先下載好并保存在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) #訓(xùn)練數(shù)據(jù)55000條print(mnist.test.images.shape, mnist.test.labels.shape) #測試數(shù)據(jù)10000條print(mnist.validation.images.shape, mnist.validation.labels.shape) #驗(yàn)證數(shù)據(jù)5000條return mnistdef Train(mnist):#Step1 定義算法公式Softmax Regressionx = tf.placeholder(tf.float32, shape=(None, 784)) #構(gòu)建占位符,代表輸入的圖像,維度None表示樣本的數(shù)量可以是任意的,維度784代表特征向量,由圖像大小28*28轉(zhuǎn)換而來weights = tf.Variable(tf.zeros([784, 10])) #構(gòu)建一個(gè)變量,代表訓(xùn)練目標(biāo)weights,初始化為0biases = tf.Variable(tf.zeros([10])) #構(gòu)建一個(gè)變量,代表訓(xùn)練目標(biāo)biases,初始化為0y = tf.nn.softmax(tf.matmul(x, weights) + biases) #構(gòu)建了一個(gè)softmax的模型:y = softmax(Wx + b),y指樣本的預(yù)測值y_ = tf.placeholder(tf.float32, [None, 10]) # 構(gòu)建占位符,代表樣本標(biāo)簽的真實(shí)值#Step2 定義損失函數(shù),選定優(yōu)化器,并指定優(yōu)化器優(yōu)化損失函數(shù)# 定義交叉熵?fù)p失函數(shù)cross_entropy = tf.reduce_mean( -tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]) )# 使用梯度下降算法(學(xué)習(xí)率為0.5)來最小化這個(gè)交叉熵?fù)p失函數(shù)train = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)#Step3 訓(xùn)練數(shù)據(jù)tf.global_variables_initializer().run()for i in range(2000): #迭代次數(shù)batch_x, batch_y = mnist.train.next_batch(100) #一個(gè)batch的大小為100, 使用一個(gè)batch的數(shù)據(jù)來訓(xùn)練模型sess.run(train, feed_dict={x: batch_x, y_: batch_y}) #用訓(xùn)練數(shù)據(jù)替代占位符來執(zhí)行訓(xùn)練if (i % 100 == 0):print("i=%d, 準(zhǔn)確率=%g" % (i, Test(mnist, weights, biases)) )print("準(zhǔn)確率=%g" % Test(mnist, weights, biases))# 在測試數(shù)據(jù)上對準(zhǔn)確率進(jìn)行評測 def Test(mnist, weights, biases):x = tf.placeholder(tf.float32, [None, 784]) #測試數(shù)據(jù)y = tf.nn.softmax(tf.matmul(x, weights) + biases) #預(yù)測值y_ = tf.placeholder(tf.float32, [None, 10]) #真實(shí)值# tf.argmax()返回的是某一維度上其數(shù)據(jù)最大所在的索引值,在這里即代表預(yù)測值和真實(shí)值# 判斷預(yù)測值y和真實(shí)值y_中最大數(shù)的索引是否一致,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)) # 用平均值來統(tǒng)計(jì)測試準(zhǔn)確率return sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}) # 打印測試信息def main():mnist = DownloadData()Train(mnist)if __name__ == '__main__':main()
總結(jié)
以上是生活随笔為你收集整理的TensorFlow MNIST (Softmax)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TensorFlow的基本使用
- 下一篇: Storm,Trident,Spark