知識來源:《21個項目玩轉(zhuǎn)深度學習 基于TensorFlow的實踐詳解》贰剥,Tensorflow中文社區(qū)瞻讽。
了解Softmax函數(shù)
image.png
image.png
利用Softmax的MNIST數(shù)字分類
tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST/",one_hot = True)
#訓練樣本鸳吸。輸入輸出
x = tf.placeholder(tf.float32,[None,784]) #輸入圖像
_y = tf.placeholder(tf.float32,[None,10]) #輸入圖像對應(yīng)labels
#構(gòu)造預測模型
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x,W)+b) #預測模型?
#損失函數(shù)優(yōu)化
cross = tf.reduce_mean(-tf.reduce_sum(_y*tf.log(y))) #損失函數(shù)
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross) #損失函數(shù)優(yōu)化
#計算準確度
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(_y,1)) #equal,判斷兩者是否相等(55000速勇,10)
accuray = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) #cast 數(shù)據(jù)轉(zhuǎn)換
#Tensoflow語法
sess = tf.InteractiveSession()
tf.global_variables_initializer().run() #變量初始化
for i in range(1000):
batch_xs,batch_ys = mnist.train.next_batch(100)
sess.run(train_step,feed_dict= {x:batch_xs,_y:batch_ys})
print(sess.run(accuray,feed_dict={x:mnist.test.images,_y:mnist.test.labels}))
其中有equal晌砾,argmax,cast烦磁,reduce_mean等Tensorflow常用函數(shù)养匈。功能可運行代碼
import tensorflow as tf
v = [1,3,2,456,63,3,2]
m = [[1,23,4],[12,4,55],[1,3,2]]
v1 = [[True,False,True,False],[True,False,True,False],[True,False,True,False]]
t = [[1,2,3,4,5],[1,2,3,4,5]]
t1 = [[1,3,2,4,5],[1,3,2,4,5]]
with tf.Session() as sess:
a = tf.argmax(v,0) #一列中最大值
#a1 = tf.argmax(v.T,1) #向量不可以用行搜索
b =tf.argmax(m,0)
b1 = tf.argmax(m,1) #一行中最大值
print(sess.run(a))
#print(sess.run(a1))
print(sess.run(b))
print(sess.run(b1))
c = tf.cast(v1,tf.float32) #將True,False轉(zhuǎn)化為float32的1,0
print(sess.run(c))
d = tf.reduce_mean(c,reduction_indices=0) #d=[1,0,1,0] 一列的均值
#d = tf.reduce_mean(c,reduction_indices=1) #d=[0.5,0.5,0.5] 一行的均值
#d = tf.reduce_mean(c) #d=0.5
print(sess.run(d))
e = tf.equal(t,t1) #比較相同位置的數(shù)值是否相等都伪,返回BOOL(即True,False)
print(sess.run(e))