【问题标题】:Derivative of softmax function in PythonPython中softmax函数的导数
【发布时间】:2019-03-04 04:14:55
【问题描述】:

下面是神经网络的 softmax 激活函数。这个函数的导数是多少?

def softmax(z):
   e = np.exp(z)
   return e / np.sum(e, axis=1)

【问题讨论】:

标签: python neural-network softmax


【解决方案1】:

softmax 导数的迭代版本

import numpy as np

def softmax_grad(s): 
    # Take the derivative of softmax element w.r.t the each logit which is usually Wi * X
    # input s is softmax value of the original input x. 
    # s.shape = (1, n) 
    # i.e. s = np.array([0.3, 0.7]), x = np.array([0, 1])

    # initialize the 2-D jacobian matrix.
    jacobian_m = np.diag(s)

    for i in range(len(jacobian_m)):
        for j in range(len(jacobian_m)):
            if i == j:
                jacobian_m[i][j] = s[i] * (1-s[i])
            else: 
                jacobian_m[i][j] = -s[i]*s[j]
    return jacobian_m

矢量化版本

def softmax_grad(softmax):
    # Reshape the 1-d softmax to 2-d so that np.dot will do the matrix multiplication
    s = softmax.reshape(-1,1)
    return np.diagflat(s) - np.dot(s, s.T)

参考https://medium.com/@aerinykim/how-to-implement-the-softmax-derivative-independently-from-any-loss-function-ae6d44363a9d

【讨论】:

  • 我使用了这个 softmax_grad() 但错误显示:内存错误
  • 为什么输入是 n × 1 向量,输出是 n × n 矩阵?
  • if i == j: jacobian_m[i][j] = s[i] * (1-s[i]) 不应该是(1 - s[j])
猜你喜欢
  • 1970-01-01
  • 2017-08-30
  • 2017-03-27
  • 2016-10-13
  • 2018-05-02
  • 2016-04-30
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
相关资源
最近更新 更多