【发布时间】:2014-06-08 07:36:09
【问题描述】:
我正在尝试使用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
下面是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]]
这是我为执行最小化而运行的代码:
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
所以这个“沃尔夫线搜索”似乎没有成功,但我不知道如何从这里开始......感谢任何帮助!
【问题讨论】:
-
您的梯度函数可能不正确。尝试根据有限差分验证它(例如使用scipy.optimize.check_grad)
-
@pv。你打赌;)谢谢!
标签: python numpy scipy mathematical-optimization