2

我在使用 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 ()  

我试图最小化func(x)关于 N 的函数以找到 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不起作用。

4

1 回答 1

2

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

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

在此处输入图像描述

于 2020-03-08T13:42:30.307 回答