我正在学习神经网络并用 python 实现它。我首先定义一个softmax函数,我按照这个问题给出的解决方案Softmax function - python .以下是我的代码:
def softmax(A):
"""
Computes a softmax function.
Input: A (N, k) ndarray.
Returns: (N, k) ndarray.
"""
s = 0
e = np.exp(A)
s = e / np.sum(e, axis =0)
return s
我得到了一个测试代码,看看 sofmax
函数是否正确。 test_array
是测试数据,test_output
是 softmax(test_array)
的正确输出。以下是测试代码:
# Test if your function works correctly.
test_array = np.array([[0.101,0.202,0.303],
[0.404,0.505,0.606]])
test_output = [[ 0.30028906, 0.33220277, 0.36750817],
[ 0.30028906, 0.33220277, 0.36750817]]
print(np.allclose(softmax(test_array),test_output))
但是根据我定义的softmax
函数。通过 softmax(test_array)
测试数据返回
print (softmax(test_array))
[[ 0.42482427 0.42482427 0.42482427]
[ 0.57517573 0.57517573 0.57517573]]
谁能告诉我我定义的函数 softmax
有什么问题?
最佳答案
问题出在你的总和上。您在轴 0 中求和,您应该保持轴 0 不变。
要对同一示例中的所有条目求和,即在同一行中,您必须改用轴 1。
def softmax(A):
"""
Computes a softmax function.
Input: A (N, k) ndarray.
Returns: (N, k) ndarray.
"""
e = np.exp(A)
return e / np.sum(e, axis=1, keepdims=True)
使用 keepdims
来保持形状并能够将 e
除以总和。
在您的示例中,e
的计算结果为:
[[ 1.10627664 1.22384801 1.35391446]
[ 1.49780395 1.65698552 1.83308438]]
然后每个示例的总和(return
行中的分母)为:
[[ 3.68403911]
[ 4.98787384]]
然后该函数将每一行除以其总和,并在 test_output
中给出结果。
正如 MaxU 指出的那样,最好在取幂之前删除最大值,以避免溢出:
e = np.exp(A - np.sum(A, axis=1, keepdims=True))
关于python - 神经网络中的 Softmax 函数 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47372685/