scipy.动态多变量列表优化最小化



我正在尝试使用scipy。优化到优化。我的问题是变量的数量不是固定的-它是根据场景动态生成的。为了捕获这一点,我必须使用if/elif语句来设置变量的数量,这使得代码非常庞大,如下所示。有什么优雅的方法吗?

import scipy.optimize as optimize
list1=['x','y'] # list1 is generated dynamically with varied length depending on different scenario. Here I just make len=2 as an example.

n=len(list1)
def f(params):
if n==3:
a, b, c = params 
return a**2 + b**2 + c**2
elif n==2:
a, b  = params 
return a**2 + b**2 
if n==3:
initial_guess = [1, 1, 1]
elif n==2:
initial_guess = [1, 1]
result = optimize.minimize(f, initial_guess,method='SLSQP')
if result.success:
fitted_params = result.x
print(fitted_params)
else:
raise ValueError(result.message)

你可以使用这个演示:

import numpy as np
from scipy import optimize
def cal_f(params):
x = np.array(params)
return np.sum(x ** 2)

def callist(list_l = ['a','b','c','d']):
n = len(list_l)
initial_guess = np.ones(shape=(n,))
try:
result = optimize.minimize(cal_f, initial_guess, method='SLSQP')
if result.success:
fitted_param = result.x
print(result)
else:
raise ValueError(result.message)
except Exception as e:
print(Exception)

# test function
callist()
callist(list_l=['a','b', 'c', 'd','e','f'])

相关内容

  • 没有找到相关文章

最新更新