scipy.optimize.minimize 和 Minuit 返回初始猜测值

scipy.optimize.minimize and Minuit returning initial guess value

我在使用 scipy.minimize.optimize 时遇到了问题。这是我的代码。

from time import process_time 
import numpy as np
from scipy.optimize import minimize
class NMin(object):
    def __init__(self, error):
        self.error=error

    def func(self, N):
        i = np.arange(1, N+1)
        f = np.abs(np.sum(4/(N*(1+((i - 0.5)/N)**2))) - np.pi)-self.error
        return(f)

    def nMin(self):
        x0 = 1
        nMin = minimize(self.func, x0)
        return(nMin.x)


def main():
    t1_start = process_time()
    error=10**(-6)
    nMin = NMin(error).nMin()
    print("the minimum value of N is: " + str(nMin))
    t1_stop = process_time() 
    print("Elapsed time during the whole program in seconds:", 
                                         t1_stop-t1_start)

main ()  

我试图最小化关于 N 的函数 func(x) 以找到 N 最小值,但 NMin(error).nMin() 似乎返回 x0 = 1 而不是 N 最小值。这是我的输出。

the minimum value of N is: [1.]
Elapsed time during the whole program in seconds: 0.015625

我真的很烦恼,因为我似乎找不到问题所在,而且我不明白为什么 scipy.optimize 不起作用。

scipy.optimize.minimize 主要用于连续可微函数。在 func 中使用 arange 会产生一个离散的问题。由于这些不连续性,这会导致梯度大幅跳跃(见下图)。

我添加了一些调试打印:

from time import process_time
import numpy as np
from scipy.optimize import minimize
class NMin(object):
    def __init__(self, error):
        self.error=error

    def func(self, N):
        print("func called N = {}".format(N))
        i = np.arange(1, N+1)
        print("i = {}".format(i))
        f = np.abs(np.sum(4/(N*(1+((i - 0.5)/N)**2))) - np.pi)-self.error
        print("f = {}".format(f))
        return(f)

    def nMin(self):
        x0 = 1
        nMin = minimize(self.func, x0)
        return(nMin.x)


def main():
    t1_start = process_time()
    error=10**(-6)
    nMin = NMin(error).nMin()
    print("the minimum value of N is: " + str(nMin))
    t1_stop = process_time()
    print("Elapsed time during the whole program in seconds:",
                                         t1_stop-t1_start)

main()

这导致:

func called N = [1.]
i = [1.]
f = 0.05840634641020706
func called N = [1.00000001]
i = [1. 2.]
f = 1.289175555623012

也许您想使用更适合离散问题的其他求解器或更改您的 objective 以满足基于梯度的优化的连续性先决条件。