python - 在 Python 中从头开始计算雅可比矩阵

标签 python numpy deep-learning derivative softmax

我正在尝试实现softmax函数的导数矩阵(Softmax的雅可比矩阵)。

我知道 Softmax(Xi) 对 Xj 的数学导数是:

enter image description here

其中红色三角洲是克罗内克三角洲。

到目前为止我已经实现的是:

def softmax_grad(s):
    # input s is softmax value of the original input x. Its shape is (1,n) 
    # e.i. s = np.array([0.3,0.7]), x = np.array([0,1])

    # make the matrix whose size is n^2.
    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

当我测试时:

In [95]: x
Out[95]: array([1, 2])

In [96]: softmax(x)
Out[96]: array([ 0.26894142,  0.73105858])

In [97]: softmax_grad(softmax(x))
Out[97]: 
array([[ 0.19661193, -0.19661193],
       [-0.19661193,  0.19661193]])

你们如何实现雅可比行列式?我想知道是否有更好的方法来做到这一点。任何对网站/教程的引用也将不胜感激。

最佳答案

您可以像下面这样对 softmax_grad 进行矢量化;

soft_max = softmax(x)
​
# reshape softmax to 2d so np.dot gives matrix multiplication
def softmax_grad(softmax):
    s = softmax.reshape(-1,1)
    return np.diagflat(s) - np.dot(s, s.T)

softmax_grad(soft_max)

#array([[ 0.19661193, -0.19661193],
#       [-0.19661193,  0.19661193]])

详细信息:sigma(j) * delta(ij) 是一个对角矩阵,其中 sigma(j) 作为对角元素,您可以使用np.diagflat(s)创建; sigma(j) * sigma(i) 是 softmax 的矩阵乘法(或外积),可以使用 np.dot 计算:

关于python - 在 Python 中从头开始计算雅可比矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45949141/

相关文章:

python 2.7.5,获取多个用户输入以加载超过 1 个数组/列表,循环问题

machine-learning - 为什么我们应该在 Keras 中标准化深度学习的数据?

python - 是否可以在 keras 中实现动态类权重?

python - 在 Numpy 中乘积 block 矩阵

Python - Pandas 相对于 Numpy/Scipy 的主要改进是什么

python - Tensorflow:训练神经网络时损失没有改善

python - matplotlib plot_surface 命令的颜色条

python - 如何重定向子进程的标准输出?

python - sklearn.plot_tree 如何可视化分类任务的 class_labels?

python - 去除 Python 中数组列表中的空数组和零数组