Skip to content

[Machine Learning] softmax 函式介紹與程式實作

Softmax

Softmax 函式,又被稱為『歸一化指數函數』,基本上是將一組向量(就好比說我們 Machine Learning 最後輸出的預測結果有多個分類,每個分類有著一個分數)映射為每個向量當中的元素都位於 (0, 1) 之間,其實就是代表著每個分類的機率分佈。當然,既然是機率分佈,那麼這個向量的所有元素相加總和應為 1。

我們來看一下 Softmax 的公式:

這個公式有點不好看懂,直接以程式表示最快。

# -*- coding: utf-8 -*-
import numpy as np

inputs = np.array([1, 4, 9, 7, 5])

def softmax(inputs):
    return np.exp(inputs)/sum(np.exp(inputs))

outputs = softmax(inputs)
for n in range(len(outputs)):
    print('{} -> {}'.format(inputs[n], outputs[n]))



Output:

1 -> 0.00028901145493871657
4 -> 0.005804950249395781
9 -> 0.8615310049461178
7 -> 0.11659554257150641
5 -> 0.015779490778041354

大致上就是在做這樣的事情。大致上總和為 1:

print(sum(outputs))



Output:

1.0

應用

  • Keras 和 PyTorch 裡頭都有這個函數可以直接調用。
  • Softmax function 產出的是『選取這個預測結果的機率』,所以,並不總是預測分數最高者作為輸出,偶爾也有其他低機率的輸出結果。
  • Softmax function 多用於多分類輸出。
  • 可以使用 Chain Rule 來進行 backward propagation 的偏微分。

References


Read More

Leave a Reply