Scipy/python 中分段函数的优化

Rob*_*xon 5 python numpy scipy pandas scikit-learn

我一直在尝试通过 scipy 优化器传递分段函数。我在下面构建的示例显示了问题:

args = (6,6,7,1,2,4,6,6)
def _alpha(params, *args):
    knot = params[0]
    rate = np.asarray(args)
    where_knot = np.where(rate>knot, 1, 0)
    return np.sum(where_knot)
?
seed_vals = (5,)
bounds = ((1,7), )
res1 = optimize.minimize(_alpha, seed_vals, args=args, method='L-BFGS-B', bounds=bounds)
res1.x
>>> array([ 5.])
Run Code Online (Sandbox Code Playgroud)

但是,这显然不是解决方案:

print _alpha((5,), args)
>>> 5
print _alpha((7,), args)
>>> 0
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

编辑:我也试过 numpy 分段函数并得到相同的结果。

小智 4

您需要使用以下方法调整近似步长:http://docs.scipy.org/doc/scipy/reference/optimize.minimize-lbfgsb.html#optimize-minimize-lbfgsb

默认值类似于 .0000001,因此它将估计结的梯度为 0