【问题标题】:pass variable to scipy curve_fit将变量传递给 scipy curve_fit
【发布时间】:2022-11-22 15:41:05
【问题描述】:

我正在尝试使用一个函数来拟合数据集:

def kel_voigt(x, en2, l2, en3, l3):
  # The first term, 300 should be a variable, from the main
  const = 300 * 1e-6 * math.pi / (2 * math.tan(math.radians(63.3)))
  return const * (((1 - (np.exp(-x / l2))) / en2) +
                  ((1 - (np.exp(-x / l3))) / en3))

其中,配件从 main 调用为:

  for n in range(len(sheets)):
    popt, pcov = sp.optimize.curve_fit(kel_voigt,
                                       np.array(tl[n]),
                                       np.array(h0l[n]),
                                       maxfev=10000)

现在,问题是,变量负载的第一项(即 300)应该是一个变量并从 main 传递(它与主迭代中 n 的每个值不同)。 来自https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html,我还没有找到将额外参数传递给 scipy.optimize.curve_fit() 的方法。

我如何设置额外的变量?

【问题讨论】:

    标签: python curve-fitting scipy-optimize


    【解决方案1】:

    您可以为您的固定变量/常量添加一个额外的参数到您的函数中,并将此函数包装在每个循环迭代中:

    def kel_voigt(x, fix_var, en2, l2, en3, l3):
      # The first term, 300 should be a variable, from the main
      const = fix_var * 1e-6 * math.pi / (2 * math.tan(math.radians(63.3)))
      return const * (((1 - (np.exp(-x / l2))) / en2) +
                      ((1 - (np.exp(-x / l3))) / en3))
    
    for n in range(len(sheets)):
        # replace 300 with the value in the current iteration
        fun_to_fit = lambda x, en2, l2, en3, l3: kel_voigt(x, 300, en2, l2, en3, l3)
        popt, pcov = sp.optimize.curve_fit(fun_to_fit,
                                           np.array(tl[n]),
                                           np.array(h0l[n]),
                                           maxfev=10000)
    

    【讨论】:

      猜你喜欢
      • 2021-02-16
      • 1970-01-01
      • 2017-01-31
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 2020-02-16
      • 2012-02-13
      相关资源
      最近更新 更多