Python softmax實現(xiàn)及數(shù)值穩(wěn)定性詳解
Softmax
softmax函數(shù)將任意n維的實值向量轉(zhuǎn)換為取值范圍在(0,1)之間的n維實值向量,并且總和為1。
例如:向量softmax([1.0, 2.0, 3.0]) ------> [0.09003057, 0.24472847, 0.66524096]
性質(zhì):
- 因為softmax是單調(diào)遞增函數(shù),因此不改變原始數(shù)據(jù)的大小順序。
- 將原始輸入映射到(0,1)區(qū)間,并且總和為1,常用于表征概率。
- softmax(x) = softmax(x+c), 這個性質(zhì)用于保證數(shù)值的穩(wěn)定性。
softmax的實現(xiàn)及數(shù)值穩(wěn)定性
一個最簡單的計算給定向量的softmax的實現(xiàn)如下:
import numpy as np def softmax(x): """Compute the softmax of vector x.""" exp_x = np.exp(x) softmax_x = exp_x / np.sum(exp_x) return softmax_x
讓我們來測試一下上面的代碼:
softmax([1, 2, 3]) array([0.09003057, 0.24472847, 0.66524096])
但是,當(dāng)我們嘗試輸入一個比較大的數(shù)值向量時,就會出錯:
softmax([1000, 2000, 3000]) array([nan, nan, nan])
這是由numpy中的浮點型數(shù)值范圍限制所導(dǎo)致的。當(dāng)輸入一個較大的數(shù)值時,sofmax函數(shù)將會超出限制,導(dǎo)致出錯。
為了解決這一問題,這時我們就能用到sofmax的第三個性質(zhì),即:softmax(x) = softmax(x+c),
一般在實際運用中,通常設(shè)定c = - max(x)。
接下來,我們重新定義softmax函數(shù):
import numpy as np def softmax(x): """Compute the softmax in a numerically stable way.""" x = x - np.max(x) exp_x = np.exp(x) softmax_x = exp_x / np.sum(exp_x) return softmax_x
然后再次測試一下:
softmax([1000, 2000, 3000]) array([ 0., 0., 1.])
Done!
以上都是基于向量上的softmax實現(xiàn),下面提供了基于向量以及矩陣的softmax實現(xiàn),代碼如下:
import numpy as np def softmax(x): """ Compute the softmax function for each row of the input x. Arguments: x -- A N dimensional vector or M x N dimensional numpy matrix. Return: x -- You are allowed to modify x in-place """ orig_shape = x.shape if len(x.shape) > 1: # Matrix exp_minmax = lambda x: np.exp(x - np.max(x)) denom = lambda x: 1.0 / np.sum(x) x = np.apply_along_axis(exp_minmax,1,x) denominator = np.apply_along_axis(denom,1,x) if len(denominator.shape) == 1: denominator = denominator.reshape((denominator.shape[0],1)) x = x * denominator else: # Vector x_max = np.max(x) x = x - x_max numerator = np.exp(x) denominator = 1.0 / np.sum(numerator) x = numerator.dot(denominator) assert x.shape == orig_shape return x
以上就是Python softmax實現(xiàn)及數(shù)值穩(wěn)定性詳解的詳細內(nèi)容,更多關(guān)于Python softmax數(shù)值穩(wěn)定性的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
淺談keras保存模型中的save()和save_weights()區(qū)別
這篇文章主要介紹了淺談keras保存模型中的save()和save_weights()區(qū)別,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python使用Kafka處理數(shù)據(jù)的方法詳解
Kafka是一個分布式的流數(shù)據(jù)平臺,它可以快速地處理大量的實時數(shù)據(jù)。在Python中使用Kafka可以幫助我們更好地處理大量的數(shù)據(jù),本文就來和大家詳細講講具體使用方法吧2023-04-04Keras搭建分類網(wǎng)絡(luò)平臺VGG16?MobileNet?ResNet50
這篇文章主要為大家介紹了Keras搭建分類網(wǎng)絡(luò)平臺VGG16?MobileNet?ResNet50,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05Python基于codecs模塊實現(xiàn)文件讀寫案例解析
這篇文章主要介紹了Python基于codecs實現(xiàn)文件讀寫案例解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-05-05Python實現(xiàn)將Excel內(nèi)容插入到Word模版中
前段時間因為需要處理一大堆驗收單,都是一些簡單的復(fù)制粘貼替換工作,于是就想到用python進行處理。本文分享了用python將excel文件單元格內(nèi)容插入到word模版中并保存為新文件的辦法,希望對大家有所幫助2023-03-03pytorch載入預(yù)訓(xùn)練模型后,實現(xiàn)訓(xùn)練指定層
今天小編就為大家分享一篇pytorch載入預(yù)訓(xùn)練模型后,實現(xiàn)訓(xùn)練指定層,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01