我有一个简单的softmax实现:
softmax = np.exp(x) / np.sum(np.exp(x), axis=0)
对于x设置为数组:https://justpaste.it/6wis7
您可以将其加载为:
import numpy as np
x = np.as (just copy and paste the content (starting from array))
我明白了:
softmax.mean(axis=0).shape
(100,) # now all elements must be 1.0 here, since its a probability
softmax.mean(axis=0) # all elements are not 1
array([0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158,
0.05263158, 0.05263158, 0.05263158, 0.05263158, 0.05263158])
为什么这个实现错了?怎么解决?
概率的总和必须是1,不是它的意思。让我们用这个简单的例子来说明一点。想象一下3 softmax
输出值s = [0.5, 0.25, 0.25]
。显然他们必须总结1
(概率)。但他们的意思是0.333
。
>>> softmax.sum(axis=0)
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
我希望这个例子能说清楚!
对我来说看上去很好:
import numpy as np
def softmax(x):
return np.exp(x) / np.sum(np.exp(x), axis=0)
logits = softmax(np.random.rand(4))
print(logits)
softmax actications的所有元素的总和应该等于1。
对于分类任务,通常采用具有最高值(np.argmax()
)或最高n-indices的索引,并选择那些最可能的类(es):
class_index = np.argmax(logits) # Assuming logits is the output of a trained model
print('Most likely class: %d' % class_index)
正如JosepJoestar在评论中指出的那样,softmax函数的定义可以在here中找到。