使用 numpy 数组实现 softmax 函数



我目前的函数如下:

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但我不知道该怎么做。

你想做类似的事情(见这篇文章(

def softmax(x, axis=None):
x = x - x.max(axis=axis, keepdims=True)
y = np.exp(x)
return y / y.sum(axis=axis, keepdims=True)

从 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)

假设你的z是一个二维数组,试试

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

最新更新