【问题标题】:Minimizing a function in scipy with three parameters returns the initial guess使用三个参数最小化 scipy 中的函数返回初始猜测
【发布时间】:2020-11-26 18:33:43
【问题描述】:

一组坐标为xy 的点看起来像this。我想在y = 0 下方的区域中构造一条曲线,形式为- a - np.exp(-(x - b)/c),其中参数abc 是通过以下条件找到的,即y = 0 以下90% 的点被包​​围通过这一行和有问题的功能。

我编写了以下代码来执行此操作,但 minimize 函数给出了最初的猜测结果,我不知道我错过了什么。

from scipy.optimize import minimize
import numpy as np

def enclosed_points(params):
    a, b, c = params
    den = (y < 0).sum()                   # Calculate the number of points with y coordinate below y0
    func = - a - np.exp(-(x - b)/c)       # Calculate the value of the function for each x
    num = ((y < 0) & (y > func)).sum()    # Calculate the number of points with y coordinate
                                          # below y0 and above the function
    return np.abs(num/den - 0.9)          # Return the absolute value of the difference between
                                          # the ratio of num and den and the target number (0.9)

initial_guess = [0.1, 0.2, 1]             # Dummy initial guess
result = minimize(enclosed_points, initial_guess)

编辑。 Here我已经上传了npy格式的整个数据的随机样本。

【问题讨论】:

  • 您能提供您的示例数据吗?使用示例数据更容易发现问题。
  • @mrhajbabaei 您可以从帖子最后一行的链接下载数据的随机样本。谢谢!文件比较大,不是全集,如果需要我可以上传全集。

标签: python scipy minimize


【解决方案1】:

好吧,我尝试了一些不同的方法并更改了您的代码的某些部分:

def func(x, a, b, c):
    return - a - np.exp(-(x - b)/c)

def enclosed_points(params):
    a, b, c = params
    loss1 = y[np.argwhere( y > 0)]
    loss2 = loss1[np.argwhere( loss1 < func(x[np.argwhere( y > 0)], a, b, c) )]
    loss = ((loss2.sum() / len(y)) - 0.9)**2
    return loss

initial_guess = [-0.1, 0.2, 1]     
result = minimize(enclosed_points, initial_guess, method='SLSQP', options={'eps': 1e-2})

loss1 和 loss2 与您的损失函数做同样的工作,但我将 abs 更改为 2 的幂(因为在我看来它更常见)(还根据另一个帖子在您的最小化器中添加了“method='SLSQP', options={'eps': 1e-2}” StackOverflow;尝试仔细阅读它们并熟悉他们关于这个最小化器的问题)。但是,我认为主要问题是您的问题是非凸的,minimize 函数试图找到局部最小值。请参阅this 帖子以获得全面的描述。 最后,我会说,以 [-0.1, 0.2, 1] 为初始点,我可以找到一个解决方案(尝试为 a 设置不同的负值,您可能会找到其他解决方案:))

祝你好运

【讨论】:

  • 非常感谢。严格来说,您的解决方案不是我想要的,但经过一些小的修改后,我设法适应了它。再次感谢您。
猜你喜欢
  • 2019-12-16
  • 2021-01-29
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 2015-06-09
  • 1970-01-01
  • 1970-01-01
  • 2011-04-17
相关资源
最近更新 更多