だから、これは本当にデザートノートの答えへのコメントですが、私の評判のためにまだコメントすることはできません. 彼が指摘したように、あなたのバージョンは、入力が単一のサンプルで構成されている場合にのみ正しいです。入力が複数のサンプルで構成されている場合、それは誤りです。ただし、デザートノートの解決策も間違っています。問題は、一度 1 次元の入力を取り、次に 2 次元の入力を取ることです。これをお見せしましょう。
import numpy as np
# your solution:
def your_softmax(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum()
# desertnaut solution (copied from his answer):
def desertnaut_softmax(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum(axis=0) # only difference
# my (correct) solution:
def softmax(z):
assert len(z.shape) == 2
s = np.max(z, axis=1)
s = s[:, np.newaxis] # necessary step to do broadcasting
e_x = np.exp(z - s)
div = np.sum(e_x, axis=1)
div = div[:, np.newaxis] # dito
return e_x / div
デザートノートの例を見てみましょう:
x1 = np.array([[1, 2, 3, 6]]) # notice that we put the data into 2 dimensions(!)
これは出力です:
your_softmax(x1)
array([[ 0.00626879, 0.01704033, 0.04632042, 0.93037047]])
desertnaut_softmax(x1)
array([[ 1., 1., 1., 1.]])
softmax(x1)
array([[ 0.00626879, 0.01704033, 0.04632042, 0.93037047]])
この状況では、desernauts バージョンが失敗することがわかります。(入力が np.array([1, 2, 3, 6] のように 1 次元のみの場合) ではありません)。
これが 2 次元入力を使用する理由なので、3 つのサンプルを使用してみましょう。次の x2 は、desernauts の例のものと同じではありません。
x2 = np.array([[1, 2, 3, 6], # sample 1
[2, 4, 5, 6], # sample 2
[1, 2, 3, 6]]) # sample 1 again(!)
この入力は、3 つのサンプルを含むバッチで構成されています。しかし、サンプル 1 と 3 は本質的に同じです。これで、3 行目のソフトマックス アクティベーションが期待されます。最初の行は 3 番目の行と同じで、x1 のアクティベーションと同じである必要があります。
your_softmax(x2)
array([[ 0.00183535, 0.00498899, 0.01356148, 0.27238963],
[ 0.00498899, 0.03686393, 0.10020655, 0.27238963],
[ 0.00183535, 0.00498899, 0.01356148, 0.27238963]])
desertnaut_softmax(x2)
array([[ 0.21194156, 0.10650698, 0.10650698, 0.33333333],
[ 0.57611688, 0.78698604, 0.78698604, 0.33333333],
[ 0.21194156, 0.10650698, 0.10650698, 0.33333333]])
softmax(x2)
array([[ 0.00626879, 0.01704033, 0.04632042, 0.93037047],
[ 0.01203764, 0.08894682, 0.24178252, 0.65723302],
[ 0.00626879, 0.01704033, 0.04632042, 0.93037047]])
これが私のソリューションの場合にのみ当てはまることを理解していただければ幸いです。
softmax(x1) == softmax(x2)[0]
array([[ True, True, True, True]], dtype=bool)
softmax(x1) == softmax(x2)[2]
array([[ True, True, True, True]], dtype=bool)
さらに、TensorFlows ソフトマックス実装の結果は次のとおりです。
import tensorflow as tf
import numpy as np
batch = np.asarray([[1,2,3,6],[2,4,5,6],[1,2,3,6]])
x = tf.placeholder(tf.float32, shape=[None, 4])
y = tf.nn.softmax(x)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(y, feed_dict={x: batch})
そして結果:
array([[ 0.00626879, 0.01704033, 0.04632042, 0.93037045],
[ 0.01203764, 0.08894681, 0.24178252, 0.657233 ],
[ 0.00626879, 0.01704033, 0.04632042, 0.93037045]], dtype=float32)