如何用Python計算Softmax?

Softmax函數,或稱歸一化指數函數,它能將一個含任意實數的K維向量z「壓縮」到另外一個K維實向量\(\sigma{(z)}\)中,使得每個元素的範圍都在(0,1)之間,而且全部元素的和爲1。該函數的形式一般按下面的式子給出:
\[ \sigma{(z)_j}=\frac{e^{z_j}}{\sum_{k=1}^{K} e^{z_k}} \quad for \, j = 1, ..., K\]python

輸入向量 [1,2,3,4,1,2,3]對應的Softmax函數的值爲[0.024,0.064,0.175,0.475,0.024,0.064,0.175]。輸出向量中擁有最大權重的項對應着輸入向量中的最大值「4」。函數

這也顯示了這個函數一般的意義:對向量進行歸一化,凸顯其中最大的值並抑制遠低於最大值的其餘份量。spa

下面是使用Python進行函數計算的示例代碼:code

import math
z = [1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0]
z_exp = [math.exp(i) for i in z]  
print(z_exp)  # Result: [2.72, 7.39, 20.09, 54.6, 2.72, 7.39, 20.09] 
sum_z_exp = sum(z_exp)  
print(sum_z_exp)  # Result: 114.98 
softmax = [round(i / sum_z_exp, 3) for i in z_exp]
print(softmax)  # Result: [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175]
[2.718281828459045, 7.38905609893065, 20.085536923187668, 54.598150033144236, 2.718281828459045, 7.38905609893065, 20.085536923187668]
114.98389973429897
[0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175]

Python使用numpy計算的示例代碼:class

import numpy as np
z = np.array([1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0])
print(np.exp(z)/sum(np.exp(z)))
[0.02364054 0.06426166 0.1746813  0.474833   0.02364054 0.06426166
 0.1746813 ]
相關文章
相關標籤/搜索