深度學習之多分類(softmax)——底層手寫實現(TensorFlow)

  • 在數學,尤其是概率論和相關領域中,Softmax函數,或稱歸一化指數函數,是邏輯函數的一種推廣。Softmax函數實際上是有限項離散概率分佈的梯度對數歸一化。
  • 它能將一個含任意實數的K維向量 “壓縮”到另一個K維實向量 中,使得每一個元素的範圍都在 之間,並且所有元素的和爲1

該函數的形式通常按下面的式子給出:
在這裏插入圖片描述
簡易代碼應用

import tensorflow as tf

# 隨機種子
tf.set_random_seed(777)

# 數據集
x_data = [[1, 2, 1, 1],
          [2, 1, 3, 2],
          [3, 1, 3, 4],
          [4, 1, 5, 5],
          [1, 7, 5, 5],
          [1, 2, 5, 6],
          [1, 6, 6, 6],
          [1, 7, 7, 7]]
y_data = [[0, 0, 1],
          [0, 0, 1],
          [0, 0, 1],
          [0, 1, 0],
          [0, 1, 0],
          [0, 1, 0],
          [1, 0, 0],
          [1, 0, 0]]

# 測試集
test_x = [[1, 11, 7, 9], [1, 3, 4, 3], [1, 1, 0, 1]]

# 佔位
x = tf.placeholder(tf.float32,[None,4])
y = tf.placeholder(tf.float32,[None,3])

# model
w = tf.Variable(tf.random_normal([4,3]),name='W')
b = tf.Variable(tf.random_normal([3]),name='B')

# 前向傳播
z = tf.matmul(x,w) + b
a = tf.nn.softmax(z)

# 代價
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(a),axis=1))

# 反向傳播
dz = a - y
dw = tf.matmul(tf.transpose(x),dz) / tf.cast(tf.shape(x)[0],tf.float32)
db = tf.reduce_mean(dz,0)


alpha = 0.08
update = [
    tf.assign(w,w-alpha*dw),
    tf.assign(b,b-alpha*db),
]

# 開啓會話
sess = tf.Session()
sess.run(tf.global_variables_initializer())

# 更新參數
for i in range(10001):
    cost_cvl,_ = sess.run([cost,update],feed_dict={x:x_data,y:y_data})

    if i % 500 == 0:
        print(i,cost_cvl)

# 展示所有
import numpy as np
np.set_printoptions(suppress=True)

# 預測值
all = sess.run(a,feed_dict={x:test_x})
print(all,sess.run(tf.argmax(all,1)))

效果展示

0 6.926112
500 0.35640523
1000 0.26802677
1500 0.21624437
2000 0.1809368
2500 0.15528953
3000 0.13585037
3500 0.12063566
4000 0.10842009
4500 0.098406896
5000 0.09005624
5500 0.08299008
6000 0.0769361
6500 0.0716931
7000 0.06711004
7500 0.0630704
8000 0.05948394
8500 0.056278758
9000 0.053397816
9500 0.050794404
10000 0.04843067

[[0.00000183 0.9999981  0.00000008]
 [0.9953721  0.0044646  0.00016333]
 [0.         0.00000149 0.99999857]] 
 
 [1 0 2]

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