【问题标题】:Restricting result of scipy minimization (SLSQP)scipy 最小化(SLSQP)的限制结果
【发布时间】:2019-10-01 05:10:05
【问题描述】:

我想最小化一个目标函数,它在每一步调用一个模拟软件并返回一个标量。有没有办法限制目标函数的结果?例如,我想获得使结果尽可能接近 1 的变量值。

我试图简单地从目标函数的结果中减去 1,但这并没有帮助。我也玩过硬币约束,但如果我理解正确的话,它们只适用于输入变量。另一种方法可能是创建一个日志,在每次迭代后存储所有变量的值(我已经这样做了)。最后,应该可以搜索结果最接近 1 的迭代并返回它的变量配置。问题是最小化可能运行时间过长并产生无用的结果。有没有更好的办法?

def objective(data):
     """
     Optimization Function
     :param data: list containing the current guess (list of float values)
     :return: each iteration returns a scalar which should be minimized
     """

     # do simulation and calculate scalar

     return result - 1.0   # doesn't work since result is becoming negative
def optimize(self):
     """
     daemon which triggers input, reads output and optimizes results
     :return: optimized results
     """

     # initialize log, initial guess etc.

     sol = minimize(self.objective, x0, method='SLSQP', options={'eps': 1e-3, 'ftol': 1e-9}, bounds=boundList)

我们的目标是找到一个可以适应任何目标值的解决方案。用户应该能够输入一个值,并且最小化将返回此目标值的最佳变量配置。

【问题讨论】:

  • (result - 1.0) ** 2 能解决问题吗?然后结果不能变成负数,最小化应该导致result = 1(或附近的东西)。
  • 这将是一个非常简单的解决方案,而且看起来很有希望。我明天试试,谢谢!

标签: python optimization scipy minimize


【解决方案1】:

正如 cmets 中所讨论的,实现此目的的一种方法是使用

return (result - 1.0) ** 2

objective。然后结果不能变为负数,优化将尝试以接近您的目标值的方式找到result(例如,在您的情况下为1.0)。

插图,首先使用您当前的设置:

from scipy.optimize import minimize


def objective(x, target_value):

    # replace this by your actual calculations
    result = x - 9.0

    return result - target_value


# add some bounds for all the parameters you have
bnds = [(-100, 100)]

# target_value is passed in args; feel free to add more
res = minimize(objective, (1), args=(1.0,), bounds=bnds)

if res.success:
    # that's the optimal x
    print(f"optimal x: {res.x[0]}")
else:
    print("Sorry, the optimization was not successful. Try with another initial"
          " guess or optimization method")

当我们选择-100 作为x 的下限并要求最小化目标时,最佳x-100(如果您从上面运行代码将打印出来)。如果我们现在替换该行

return result - target_value

return (result - target_value) ** 2

其余部分保持不变,最佳x10,正如预期的那样。

请注意,我将您的目标值作为附加参数传递,以便您的函数更加灵活。

【讨论】:

  • @Sley:很高兴听到! :)
猜你喜欢
  • 2015-01-09
  • 2019-12-16
  • 2019-10-06
  • 2018-02-16
  • 2021-01-29
  • 1970-01-01
  • 2018-05-18
  • 1970-01-01
  • 2016-06-16
相关资源
最近更新 更多