python - 神经网络中的 Softmax 函数 (Python)

标签 python machine-learning neural-network

我正在学习神经网络并用 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_outputsoftmax(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/

相关文章:

python - 更改 session cookie的超时时间是否存在安全风险?

Python - 列表的追加和排序

python - 带有可选参数的 Boost.Python 构造函数

algorithm - 为什么我用训练有素的互补和标准朴素贝叶斯模型得到相同的测试结果?

python - clf.score(X_train,Y_train) 在决策树中评估什么?

python - 使用 tensorflow 和 inception-v3 的边界框

annotations - 如何注释图像分割的基本事实?

javascript - Python:发送 JSON 数据时使用 POST 请求的 FastAPI 错误 422

python - 如何循环遍历Keras fit函数?

python - 简单的 MLP 时间序列训练产生意想不到的平均线结果