【问题标题】:Finding the step in a step function in python在python中查找步骤函数中的步骤
【发布时间】:2022-01-04 16:08:29
【问题描述】:

我正在尝试使用阶跃函数解决优化问题。一个高度简化的版本是:

def stepfunc(x):
    value=30
    if x<=30:
        return True
    else:
        return False

我正在寻找在这种情况下显然是 30 的步骤。现实世界的功能当然要复杂得多。 我想出了以下方法来解决步长值:

  1. 从 0 迭代到更大的数字,检查结果何时变为 false 并忍受步进引起的小错误
  2. 通过从两侧搜索更复杂一点(代码未优化,但应该显示想法)
step=1
x=2
#find lower and upper bounds
xl=x-step
xu=x+step
yl=y=yu=True
while(yl==y==yu):
    y=stepfunc(x)
    yl=stepfunc(xl)
    yl=stepfunc(xu)
    step=step*10
    xl=x-step
    if(xl<0):
        xl=0
    xu=x+step
#continue with xl and xu
for i in range(20):
    x=((xu-xl)/2)+xl
    y=stepfunc(x)
    yl=stepfunc(xl)
    yl=stepfunc(xu)
    if(y): #mean value gives True
        xl=x
    else:
        xu=x
    #print([xl,x,xu])
print("The step is at " + str(x))

虽然这有效,但我很确定其中一个优化库中有更好的解决方案。我尝试使用一些 scipy 求解器但没有成功,而且我可能使用了错误的搜索词。这里有可以轻松使用的库吗?

【问题讨论】:

  • 我是一步还是多步?您能否为合理的输入范围提供函数输出的图形表示?
  • 您可以从间隔[a,b] 开始,其中函数的一侧为 True,另一侧为 False。然后将区间分成 2 (m = (a+b)/2,并根据 m 的函数值继续使用[a,m][m,b]。当ab 之间的差异非常小时,您将停止。
  • 如果是单个值,这实际上是一个简单的二分搜索(如@JohanC 所述),尽管这仍然是类似的原理,但多步骤会变得更有趣

标签: python numpy scipy mathematical-optimization


【解决方案1】:

非常感谢。 @mozway 建议的“二进制搜索”确实是我正在寻找的东西,scipy.optimize.brentq 会这样做。然而,这将需要返回 -1 和 1 而不是 True 和 False。总的来说,修改后的问题与解决方案是

import scipy.optimize

# step function which returns -1 or 1 depending on which side of the step we are
def stepfunc(x):
    unknown_value_to_look_for=30 # in the real world function this number is unknown
    if(x<=unknown_value_to_look_for):
        return -1
    else:
        return 1
    
#find upper limit; lower limit is set to "0"
upper=1
for i in range(100): #max 100 tries
    if(stepfunc(upper)==1):
        break
    upper*=10

# upper is 100 in this example
scipy.optimize.brentq(stepfunc,0,upper,disp=True)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多