2017-04-13 8 views
1

以下はソフトコードを計算しようとしている小さなコードです。 1つのアレイでうまく動作します。しかし、1000年などのような大きな数字で、それは大きな数のソフトマックスエラー

import numpy as np 

def softmax(x): 
print (x.shape) 
softmax1 = np.exp(x)/np.sum(np.exp(x)) 
return softmax1 


def test_softmax(): 
    print "Running your code" 
    #print softmax(np.array([1,2])) 
    test1 = softmax(np.array([1,2])) 
    ans1 = np.array([0.26894142, 0.73105858]) 
    assert np.allclose(test1, ans1, rtol=1e-05, atol=1e-06) 
    print ("Softmax values %s" % test1) 

    test2 = softmax(np.array([[1001,1002],[3,4]])) 
    print test2 
    ans2 = np.array([ 
     [0.26894142, 0.73105858], 
     [0.26894142, 0.73105858]]) 
    assert np.allclose(test2, ans2, rtol=1e-05, atol=1e-06) 

if __name__ == "__main__": 
test_softmax() 

私はエラー RuntimeWarningを取得吹く:オーバーフローがあなたのコード softmax1 = np.exp(x)の/np.sum(NPを実行EXP に遭遇しました。 EXP(X))ソフトマックスの

+0

http://stackoverflow.com/questions/34968722/softmax-function-pythonとhttp://stackoverflow.com/questions/42599498/numerce-stable-softmax –

答えて

1

典型的な実装では、この問題を解決するための第1の最大値を奪う:

def softmax(x, axis=-1): 
    # save typing... 
    kw = dict(axis=axis, keepdims=True) 

    # make every value 0 or below, as exp(0) won't overflow 
    xrel = x - x.max(**kw) 

    # if you wanted better handling of small exponents, you could do something like this 
    # to try and make the values as large as possible without overflowing, The 0.9 
    # is a fudge factor to try and ignore rounding errors 
    # 
    #  xrel += np.log(np.finfo(float).max/x.shape[axis]) * 0.9 

    exp_xrel = np.exp(xrel) 
    return exp_xrel/exp_xrel.sum(**kw) 

は代数的に、これはまったく同じですが、これは最大値がこれまでに通過したことを保証しますexp1です。

+0

応答に感謝します。テストケースの場合を除いて、値が期待どおりになっていることがわかります。-code 'np.array([[1001,1002]、[3,4]])。 [ [0.26894142、0.73105858]、 [0.26894142、0.73105858]の代わりに、出力が[[0.26894142 0.73105858] [0. 0.]]のように見える場合。 –

+0

ああ、あなたは、列方向の代わりに列方向のソフトマックスが必要だと気づいていなかった。更新しました – Eric