python 如何给予Scipy.minimize一个初始单纯形?

ogsagwnx  于 2023-01-12  发布在  Python
关注(0)|答案(1)|浏览(161)

我试着输入一个初始的单纯形到Nelder Mead,但是在python中遇到了一个例外,形状是错误的。然而,我不知道,也不能计算出形状,也不知道在哪里查找它。
当我想使用Scipy Nelder Mead算法时,我希望有一个非常灵活的初始单纯形,或者从某个点重新开始优化,而不需要再次迭代初始单纯形。
然而,我得到了一个例外,即初始单纯形的形状是错误的:

ValueError: `initial_simplex` should be an array of shape (N+1,N)

我找不到一个很好的描述或例子如何输入一个初始单纯形的算法。有人能提供一个最小的例子,包括initial_simplex参数?

fcg9iug3

fcg9iug31#

经过测试,我发现了它的工作方式。2这个例子将一个单纯形带入算法,然后进行计算,从那里开始算法:

from math import pi, sin
from random import uniform

import matplotlib.pyplot as plt
from scipy.optimize import minimize

def function(x, a, b, c):
    return a * x ** 2 + b * x + c

def cost_function(guess):
    y_test = [function(x_i, *guess) for x_i in x_range]
    differences = [(y_i - data_i)**2 for y_i, data_i in zip(y_test, data)]
    opt_plot.set_ydata(y_test)
    plt.pause(1e-6)
    cost = sum(differences) / len(differences)

    print('cost', cost, 'guess', guess, end='\n')
    return cost

def get_initial_simplex(guess, delta_0=.2):
    print('get simplex')
    simplex = []
    simplex.append([cost_function(guess), guess])
    for i in range(len(guess)):
        simplex_guess = guess.copy()
        simplex_guess[i] += delta_0
        cost = cost_function(simplex_guess)
        simplex.append([cost, simplex_guess])

    simplex = sorted(simplex, key=lambda x: x[0])
    print('done')
    return [elem[1] for elem in simplex]

# create data
x_range = [i / 100 for i in range(-100, 100)]
data = [3 * sin(x_i + pi / 2) + 2 for x_i in x_range]

# plot the data:
fig, ax = plt.subplots()
ax.plot(x_range, data)
opt_plot, = ax.plot(x_range, [0 for _ in data])
guess = [uniform(-1,1) for _ in range(3)]

# start optimization of mse function

options ={
    'initial_simplex': get_initial_simplex(guess)
}

result = minimize(cost_function, guess, method='Nelder-Mead', options=options)

相关问题