由于scipy SLSQP中不受约束的约束而导致的数学域错误最小化 [英] Math domain error due to disrespected constraint in scipy SLSQP minimize
问题描述
考虑一个简单的问题:
max log(x)
subject to x >= 1e-4
使用 scipy.optimize.minimize
解决问题:
import numpy as np
from scipy.optimize import minimize
from math import log
def func(x):
return log(x[0])
def func_deriv(x):
return np.array([1 / x[0]])
cons = ({'type': 'ineq',
'fun' : lambda x: x[0] - 1e-4,
'jac' : lambda x: np.array([1])})
minimize(func, [1.0], jac=func_deriv, constraints=cons, method='SLSQP')
该脚本遇到 ValueError
,因为 log(x)
用负的 x
求值.似乎即使不满足约束条件也要对函数值进行评估.
The script encounters ValueError
because log(x)
is evaluated with negative x
. It seems that the function value is evaluated even if the constraint is not satisfied.
我知道在 minimize()
中使用 bounds
可以避免该问题,但这只是我原来问题的一种简化.在我最初的问题中,约束 x> = 1e-4
不能轻易地表示为 x
的边界,而是形式为 g(x)> = C
,所以 bounds
会无济于事.
I understand that using bounds
in minimize()
could avoid the problem, but this is just a simplification of my original problem. In my original problem, the constraint x >= 1e-4
cannot be represented easily as bounds of x
, but rather of the form g(x) >= C
, so bounds
wouldn't help.
推荐答案
如果我们只关心 x>ε
,可以定义扩展域的安全函数.
If we only care about the function value with x > ε
, it is possible to define a safe function extending the domain.
以 log
函数为例.可以使用另一个三次方函数扩展 log
,同时使桥点ε平滑:
Take the log
function as an example. It is possible to extend log
with another cubic function, while making the bridge point ε smooth:
safe_log(x) = log(x) if x > ε else a * (x - b)**3
要计算 a
和 b
,我们必须满足:
To calculate a
and b
, we have to satisfy:
log(ε) = a * (ε - b)**3
1 / ε = 3 * a * (ε - b)**2
因此有safe_log函数:
Hence the safe_log function:
eps = 1e-3
def safe_log(x):
if x > eps:
return log(x)
logeps = log(eps)
a = 1 / (3 * eps * (3 * logeps * eps)**2)
b = eps * (1 - 3 * logeps)
return a * (x - b)**3
它看起来像这样:
这篇关于由于scipy SLSQP中不受约束的约束而导致的数学域错误最小化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!