我试图用scipy.optimize
最小化以下函数:
这是谁的梯度:
(对于感兴趣的人,这是Bradley-Terry-Luce成对比较模型的似然函数。与逻辑回归密切相关。)
很明显,向所有参数添加常量不会更改函数的值。因此,我让θ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
下面是一个cijs
的示例:
这是我执行最小化的代码:
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)
但是,它总是在第一次迭代中失败:
Warning: Desired error not necessarily achieved due to precision loss.
Current function value: 73.290610
Iterations: 0
Function evaluations: 38
Gradient evaluations: 27
我不明白为什么失败了。由于以下行而显示错误: https://github.com/scipy/scipy/blob/master/scipy/optimize/optimize.py#L853
所以这个“沃尔夫线搜索”似乎没有成功,但我不知道如何从这里开始。。。感谢任何帮助!在
作为pv。作为评论,我在计算梯度时犯了一个错误。首先,目标函数梯度的正确(数学)表达式是:
(注意减号。)此外,我的Python实现完全错误,除了符号错误。以下是我更新的渐变:
为了调试它,我使用了:
scipy.optimize.check_grad
:表明我的梯度函数产生的结果与近似(有限差分)梯度非常遥远。在scipy.optimize.approx_fprime
要了解这些值,应该是这样的。在看来你可以把它转化成一个(非线性)最小二乘问题。通过这种方式,您必须为每个
n
变量定义间隔和每个变量的采样点数量,以便构建系数矩阵。在在本例中,我对所有变量使用相同的点数和相同的间隔:
编辑:关于上面构建的系数矩阵的更多详细信息:
相关问题 更多 >
编程相关推荐