繁体   English   中英

未能将初始参数元组传递到 scipy.optimize curve_fit

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

我想将多项式和正弦的总和拟合到数据集。 我无法将一组系数的初始值(初始猜测)传递给 function。 我知道星号 ( * ) 包含变量。

我定义了 function

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 dataframe,列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)调用 function 时,它可以工作。

怎么了?

curve_fit function 内部调用目标 function 就像

func(x, *P0)

这意味着 P0 元组中的所有值都扩展为位置 arguments 到 function。

function 声明

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

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

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

A=A[0]

行并将对 function 的直接调用更改为

func(1, *P0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM