无法将初始参数元组传递到 scipy.optimize curve_fit

Failing to pass a tuple of initial parameters into scipy.optimize curve_fit

我想对数据集拟合多项式和正弦的总和。 我没有设法将一组系数的初始值(初始猜测)传递给函数。我知道星号(*)打包变量。

我定义函数

import pandas as pd
import numpy as np
from numpy.polynomial import Polynomial as P

def func(x,*A):
    A=A[0]  # to get the values only
    polynom=P(A[0:-3]) # all but the last three coefficients go into the polynomial
    sine=A[-3]*np.sin(A[-2]*(x-A[-1])) # the last three coefficients are for the sine
    y=polynom(x)+sine # sum up both
    return y

我们来做一些测试值:

P0=(1,2,3,4,5,6,7,8,9,10,11)

调用curve_fit失败:

coefs_scipy,pcov = sio.curve_fit(func,df.length,df.s,p0=P0)

其中 df 是一个 pandas 数据框,lengths 列分别包含 xy 值。

最后一个错误是

\AppData\Local\Temp/ipykernel_16648/911748954.py in func(x, *A)
     29 def func(x,*A):
     30     A=A[0]  # to get the values only
---> 31     polynom=P(A[0:-3]) # all but the last three coefficients go into the polynomial
     32     sine=A[-3]*np.sin(A[-2]*(x-A[-1])) # the last three coefficients are for the sine
     33     y=polynom(x)+sine # sum up both

IndexError: invalid index to scalar variable.

表示无法从标量中提取 [0:-3]。虽然 A 不是我假设的标量

令人惊讶的是,当我用 func(1,P0) 调用函数时 它有效。

怎么了?

curve_fit函数内部调用目标函数like

func(x, *P0)

这意味着 P0 元组中的所有值都被扩展为函数的位置参数。

函数声明

def func(x, *A):
    ...

将所有这些位置参数收集到 A 中。所以 A 是一个包含所有值的元组,而不是元组的元组。

要解决您的问题,您应该删除

A=A[0]

行,将函数的直接调用改为

func(1, *P0)