2016-03-26 7 views
4

softmax回帰関数def softmax_1(x)を書きました。本質的にはm x nの行列をとり、行列を累乗して各列の指数を合計します。私は Numpyで行軸のnp.sumが機能しない

DF_activation_1 = pd.DataFrame(softmax_1(scores).T,index=x,columns=["x","1.0","0.2"]) 

は、だから私は試してみて、転置バージョンにとるソフトマックス関数のバージョンを作りたかった移調しており、データフレームに変換

x = np.arange(-2.0, 6.0, 0.1) 
scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)]) 
#scores shape is (3, 80) 

def softmax_1(x): 
    """Compute softmax values for each sets of scores in x.""" 
    return(np.exp(x)/np.sum(np.exp(x),axis=0)) 

はソフトマックス関数を計算

scores_T = scores.T 
#scores_T shape is (80,3) 

def softmax_2(y): 
    return(np.exp(y/np.sum(np.exp(y),axis=1))) 

DF_activation_2 = pd.DataFrame(softmax_2(scores_T),index=x,columns=["x","1.0","0.2"]) 

その後、私はこのエラーを取得する:

Traceback (most recent call last): 
    File "softmax.py", line 22, in <module> 
    DF_activation_2 = pd.DataFrame(softmax_2(scores_T),index=x,columns=["x","1.0","0.2"]) 
    File "softmax.py", line 18, in softmax_2 
    return(np.exp(y/np.sum(np.exp(y),axis=1))) 
ValueError: operands could not be broadcast together with shapes (80,3) (80,) 

np.sumメソッドで軸を転置して切り替えたときに、これが機能しないのはなぜですか?

答えて

4

変更

np.exp(y/np.sum(np.exp(y),axis=1)) 

np.exp(y)/np.sum(np.exp(y),axis=1, keepdims=True) 

にこれはnp.sumは分裂のために正しくブロードキャストする形状(80, 1)ではなく(80,)の配列を返すことを意味します。また、ブラケットの閉じ方に注意してください。

+0

すみません、ありがとう、なぜ転記​​後に私の行が1になったのですか? 'DF_activation_1'の最初の行は' 0.033211 0.667060 0.299729'ですが、 'DF_activation_2'の最初の行は' '0.612139 1.278129 1.050304' –

+0

です。私はそれを使いこなすでしょう。私はまだそれを集計しています。でる。 –

+1

ブラケットに関するコメントは、上記の答えに別の答えとして誤って掲載されました。 – YXD

関連する問題