【发布时间】:2016-03-29 09:07:56
【问题描述】:
我正在尝试为用 Numpy 编写的神经网络实现 softmax 函数。令 h 为给定信号 i 的 softmax 值。
我一直在努力实现 softmax 激活函数的偏导数。
我目前遇到的问题是,随着训练的进行,所有偏导数都接近 0。我用this excellent answer 交叉引用了我的数学,但我的数学似乎没有成功。
import numpy as np
def softmax_function( signal, derivative=False ):
# Calculate activation signal
e_x = np.exp( signal )
signal = e_x / np.sum( e_x, axis = 1, keepdims = True )
if derivative:
# Return the partial derivation of the activation function
return np.multiply( signal, 1 - signal ) + sum(
# handle the off-diagonal values
- signal * np.roll( signal, i, axis = 1 )
for i in xrange(1, signal.shape[1] )
)
else:
# Return the activation signal
return signal
#end activation function
signal 参数包含发送到激活函数的输入信号,形状为 (n_samples, n_features)。
# sample signal (3 samples, 3 features)
signal = [[0.3394572666491664, 0.3089068053925853, 0.3516359279582483], [0.33932706934615525, 0.3094755563319447, 0.3511973743219001], [0.3394407172182317, 0.30889042266755573, 0.35166886011421256]]
以下代码片段是一个完全有效的激活函数,仅作为参考和证明(主要是为了我自己)该概念性想法确实有效。
from scipy.special import expit
import numpy as np
def sigmoid_function( signal, derivative=False ):
# Prevent overflow.
signal = np.clip( signal, -500, 500 )
# Calculate activation signal
signal = expit( signal )
if derivative:
# Return the partial derivation of the activation function
return np.multiply(signal, 1 - signal)
else:
# Return the activation signal
return signal
#end activation function
编辑
- 简单的单层网络直观地存在问题。 softmax(及其导数)应用于最后一层。
【问题讨论】:
标签: python numpy neural-network softmax