使用scipy.optimize最小化多变量,可微函数

lum*_*lum 7 python numpy mathematical-optimization scipy

我正在尝试最小化以下功能scipy.optimize:

在此输入图像描述

其梯度是这样的:

在此输入图像描述

(对于那些感兴趣的人,这是成对比较的Bradley-Terry-Luce模型的似然函数.与逻辑回归密切相关.)

很明显,为所有参数添加常量不会改变函数的值.因此,我让\ theta_1 = 0.这里是目标函数的实现和python中的渐变(theta变为x这里):

def objective(x):
    x = np.insert(x, 0, 0.0)
    tiles = np.tile(x, (len(x), 1))
    combs = tiles.T - tiles
    exps = np.dstack((zeros, combs))
    return np.sum(cijs * scipy.misc.logsumexp(exps, axis=2))

def gradient(x):
    zeros = np.zeros(cijs.shape)
    x = np.insert(x, 0, 0.0)
    tiles = np.tile(x, (len(x), 1))
    combs = tiles - tiles.T
    one = 1.0 / (np.exp(combs) + 1)
    two = 1.0 / (np.exp(combs.T) + 1)
    mat = (cijs * one) + (cijs.T * two)
    grad = np.sum(mat, axis=0)
    return grad[1:]  # Don't return the first element
Run Code Online (Sandbox Code Playgroud)

这是一个cijs可能的示例:

[[ 0  5  1  4  6]
 [ 4  0  2  2  0]
 [ 6  4  0  9  3]
 [ 6  8  3  0  5]
 [10  7 11  4  0]]
Run Code Online (Sandbox Code Playgroud)

这是我运行以执行最小化的代码:

x0 = numpy.random.random(nb_items - 1)
# Let's try one algorithm...
xopt1 = scipy.optimize.fmin_bfgs(objective, x0, fprime=gradient, disp=True)
# And another one...
xopt2 = scipy.optimize.fmin_cg(objective, x0, fprime=gradient, disp=True)
Run Code Online (Sandbox Code Playgroud)

但是,它在第​​一次迭代中总是失败:

Warning: Desired error not necessarily achieved due to precision loss.
         Current function value: 73.290610
         Iterations: 0
         Function evaluations: 38
         Gradient evaluations: 27
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚它失败的原因.由于以下行显示错误:https: //github.com/scipy/scipy/blob/master/scipy/optimize/optimize.py#L853

所以这个"沃尔夫线搜索"似乎没有成功,但我不知道如何从这里开始...任何帮助表示赞赏!

lum*_*lum 4

作为@pv。作为评论指出,我在计算梯度时犯了一个错误。首先,我的目标函数梯度的正确(数学)表达式是:

在此输入图像描述

(注意减号。)此外,我的 Python 实现完全错误,超出了符号错误。这是我更新的渐变:

def gradient(x):
    nb_comparisons = cijs + cijs.T
    x = np.insert(x, 0, 0.0)
    tiles = np.tile(x, (len(x), 1))
    combs = tiles - tiles.T
    probs = 1.0 / (np.exp(combs) + 1)
    mat = (nb_comparisons * probs) - cijs
    grad = np.sum(mat, axis=1)
    return grad[1:]  # Don't return the first element.
Run Code Online (Sandbox Code Playgroud)

为了调试它,我使用了:

  • scipy.optimize.check_grad:表明我的梯度函数产生的结果与近似(有限差分)梯度相差甚远。
  • scipy.optimize.approx_fprime了解价值观应该是什么样子。
  • 一些精心挑选的简单示例(如果需要的话可以手动分析),以及一些用于健全性检查的 Wolfram Alpha 查询。