我将LikelihoodProfiler:https://github.com/insysbio/LikelihoodProfiler.jl从朱莉娅改写为Python。对于非线性约束,我需要写约束函数:Reference/#nonlinear-constraints,就像我们得到一些值一样,我们抛出强制停止异常:Reference/#exc Nlopt必须处理异常并用特殊代码返回结果。
在朱莉娅看来:pass.jl
function constraints_func(x, g)
loss = loss_func(x)
if (loss < 0.) && (scan_func(x) > scan_bound)
throw(ForcedStop("Out of the scan bound but in ll constraint."))
#elseif isapprox(loss, 0., atol=loss_tol)
# @warn "loss_tol reached... but..."
# return loss
else
return loss
end
end
opt = Opt(:LN_AUGLAG, n_theta)
ftol_abs!(opt, scan_tol)
max_objective!(
opt,
(x, g) -> scan_func(x)
)
lb = [theta_bounds[i][1] for i in 1:n_theta] # minimum.(theta_bounds)
ub = [theta_bounds[i][2] for i in 1:n_theta] # maximum.(theta_bounds)
lower_bounds!(opt, lb)
upper_bounds!(opt, ub)
local_optimizer!(opt, local_opt)
maxeval!(opt, max_iter)
# inequality constraints
inequality_constraint!(
opt,
constraints_func,
loss_tol
)
# start optimization
(optf, optx, ret) = optimize(opt, theta_init)
接下来,我尝试将其重写为python:
# Constraints function
def constraints_func(x, g, opt):
loss = loss_func(x)
if (loss < 0) and (scan_func(x) > scan_bound):
opt.force_stop()
#raise nlopt.ForcedStop("Out of the scan bound but in ll constraint.")
else:
return loss
# constrain optimizer
opt = nlopt.opt(nlopt.LN_AUGLAG, n_theta)
opt.set_ftol_abs(scan_tol)
opt.set_max_objective(lambda x, g: scan_func(x))
lb = [theta_bounds[i][0] for i in range(n_theta)] # minimum.(theta_bounds)
ub = [theta_bounds[i][1] for i in range(n_theta)] # maximum.(theta_bounds)
opt.set_lower_bounds(lb)
opt.set_upper_bounds(ub)
opt.set_local_optimizer(local_opt)
opt.set_maxeval(max_iter)
# print(max_iter)
# inequality constraints
opt.add_inequality_constraint(lambda x, g: constraints_func(x, g, opt), loss_tol)
# start optimization
optx = opt.optimize(theta_init)
optf = opt.last_optimum_value()
ret = opt.last_optimize_result()
但是当我运行它时,我得到了nlopt无效参数,如果相反
opt.force_stop()
我使用
raise nlopt.ForcedStop("Out of the scan bound but in ll constraint.")
我得到了nlopt.ForcedStop:超出扫描范围,但在11约束中
但是我删除了Nlopt处理异常并用特殊代码返回优化结果。
发布于 2019-07-30 11:23:57
显然,我无法解决这个问题,但我使用了standart python方法
try:
optx = opt.optimize(theta_init)
optf = opt.last_optimum_value()
ret = opt.last_optimize_result()
except nlopt.ForcedStop:
ret = -5
def constraints_func(x, g):
loss = loss_func(x)
if (loss < 0) and (scan_func(x) > scan_bound):
#return opt.force_stop()
raise nlopt.ForcedStop("Out of the scan bound but in ll constraint.")
else:
return loss
https://stackoverflow.com/questions/57253961
复制相似问题