gpt4 book ai didi

neural-network - 如何独立于任何损失函数实现 Softmax 导数?

转载 作者:行者123 更新时间:2023-12-04 00:49:39 28 4
gpt4 key购买 nike

对于神经网络库,我实现了一些激活函数和损失函数及其衍生物。它们可以任意组合,输出层的导数只是损失导数和激活导数的乘积。

但是,我未能独立于任何损失函数实现 Softmax 激活函数的导数。由于归一化,即方程中的分母,改变单个输入激活会改变所有输出激活,而不仅仅是一个。

这是我的 Softmax 实现,其中导数未通过梯度检查约 1%。如何实现 Softmax 导数,以便它可以与任何损失函数结合使用?

import numpy as np


class Softmax:

def compute(self, incoming):
exps = np.exp(incoming)
return exps / exps.sum()

def delta(self, incoming, outgoing):
exps = np.exp(incoming)
others = exps.sum() - exps
return 1 / (2 + exps / others + others / exps)


activation = Softmax()
cost = SquaredError()

outgoing = activation.compute(incoming)
delta_output_layer = activation.delta(incoming) * cost.delta(outgoing)

最佳答案

在数学上,Softmax σ(j) 相对于 logit Zi(例如,Wi*X)的导数为

enter image description here

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

如果您迭代实现:

def softmax_grad(s):
# input s is softmax value of the original input x. Its shape is (1,n)
# i.e. 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]])

如果您在矢量化版本中实现:
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]])

关于neural-network - 如何独立于任何损失函数实现 Softmax 导数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33541930/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com