用numpy数组实现softmax函数

时间:2018-05-19 08:25:29

标签: python arrays numpy machine-learning

我目前的职能如下:

def soft_max(z):
    t = np.exp(z)
    a = np.exp(z) / np.sum(t, axis=1)
    return a

但是我收到错误:ValueError: operands could not be broadcast together with shapes (20,10) (20,)因为np.sum(t,axis = 1)不是标量。

我想要t / the sum of each row,但我不知道该怎么做。

3 个答案:

答案 0 :(得分:2)

你想做点什么(见here post)

scale

答案 1 :(得分:1)

从1.2.0版开始,scipy包含softmax作为特殊功能:

https://scipy.github.io/devdocs/generated/scipy.special.softmax.html

使用axis参数在行上运行它。

from scipy.special import softmax
softmax(arr, axis=0)

答案 2 :(得分:0)

假设您的z是二维数组,请尝试

def soft_max(z):
    t = np.exp(z)
    a = np.exp(z) / np.sum(t, axis=1).reshape(-1,1)
    return a