1

我正在寻找正确的方法来使用可变数量的参数作为 scipy 中优化器的输入。

我有一组输入参数 p1,...,pn,并使用函数 func(p1,...,pn) 计算质量标准。我想最小化这个值。

输入参数为 0 或 1,表示是否应该使用它们。我不能简单地从参数列表中删除所有未使用的项,因为我的质量标准函数要求它们为“0”以从方程中删除未使用的项。

def func(parameters):
    ...calculate one scalar as quality criteria...

solution = optimize.fmin_l_bfgs_b(func,parameters,approx_grad=1,bounds=((0.0, 5.0),...,(0.0,5.0)) # This will vary all parameters

在我的代码中,优化器运行没有错误,但当然所有给定的参数都会更改以实现最佳解决方案。

有没有办法让 func 有 10 个输入参数,但优化器中只使用了 5 个?

到目前为止,我只能考虑以一种不需要未使用参数的“0”输入的方式更改我的 func 定义。我会很感激任何如何避免这种情况的想法。

非常感谢您的帮助!

4

2 回答 2

1

如果我理解正确,您要求的是受约束的最佳拟合,而不是找到最[p0,p1,p2...p10]适合的功能,而是希望在某种条件下func()找到最[p0, p1, ...p5]适合功能的,依此类推。func()p6=fixed6, p7=fixed7, p8=fixed8...

如果pythonargs=(somthing)scipy.optimize.fmin_l_bfgs_b. 首先,写一个部分固定的函数func_fixed()

def func_fixed(p_var, p_fixed):
    return func(p_var+p_fixed) 
# this will only work if both of them are lists. If they are numpy arrays, use hstack, append or similar

solution = optimize.fmin_l_bfgs_b(func_fixed,x0=guess_parameters,\
                                  approx_grad=your_grad,\
                                  bounds=your_bounds,\
                                  args=(your_fixed_parameters), \ #this is the deal
                                  other_things)

没必要有func_fixed(),可以用lambda。但这样读起来容易得多。

于 2013-09-11T16:02:26.977 回答
0

我最近解决了一个类似的问题,我想在每次运行时优化不同的参数子集,但需要所有参数来计算目标函数。我在目标函数中添加了两个参数:

  1. 一个索引数组 x_idx,它指示要优化哪些参数,即 0 不优化和 1 优化
  2. 具有所有参数初始值的数组 x0

在目标函数中,我根据索引数组将参数列表设置为要优化的参数或初始值。

import numpy 
import scipy.optimize

def objective_function(x_optimised, x_idx, x0):
    x = []
    j = 0
    for i, idx in enumerate(x_idx):
        if idx is 1:
            x.append(x_optimised[j])
            j = j + 1
        else:
            x.append(x0[i])
    x = numpy.array(x)
    return sum(x**2)

if __name__ == '__main__':
    x_idx = [1, 1, 0]
    x0 = [1.1, 1.3, 1.5]

    x_initial = [x for i, x in enumerate(x0) if x_idx[i] is 1]
    xopt, fopt, iter, funcalls, warnflag = scipy.optimize.fmin(objective_function, \
                                                   x_initial, args=(x_idx, x0,), \
                                                   maxfun = 200, full_output=True)
    print xopt
于 2013-12-12T11:07:53.057 回答