【问题标题】:Error in Fitting a curve using curve_fit in python在python中使用curve_fit拟合曲线时出错
【发布时间】:2021-11-11 16:12:38
【问题描述】:

我正在尝试使用 Scipy Curve_fit 函数将下一个函数拟合到一些数据中:

def sinugauss(x, A, B, C):
    exponente = A*(np.sin(x-B))**2
    return np.array([C/(np.exp(exponente))])

我有一个包含 33 个点的数据集,但我不断收到此错误:

Traceback (most recent call last):\
  File "D:Es_periodico_o_no.py", line 35, in <module>\
    res, cov = curve_fit(sinugauss,datos['x'],datos['y'])\
  File "D:\lib\site-packages\scipy\optimize\minpack.py", line 789, in curve_fit\
    res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)\
  File "D:\lib\site-packages\scipy\optimize\minpack.py", line 414, in leastsq
    raise TypeError(f"Improper input: func input vector length N={n} must"\
TypeError: Improper input: func input vector length N=3 must not exceed func output vector length M=1

这是完整的代码:

def sinugauss(x, Ventas, Inicio, Desv):
    exponente = Desv*(np.sin(x-Inicio))**2
    return np.array([Ventas/(np.exp(exponente))])

for index, row in real_df.iterrows():
    datos_y = np.array([row]).transpose()
    datos_x = np.array([range(len(datos_y))]).transpose()
    datos = pd.DataFrame(np.column_stack([datos_x,datos_y]),columns=['x','y'])
    res, cov = curve_fit(sinugauss,datos['x'],datos['y'])
    print(res)
    print(cov)

第一次迭代后出现错误,所有行都有 33 个非 nan 点。可能有零

谢谢

【问题讨论】:

    标签: python scipy curve-fitting


    【解决方案1】:

    在函数sinugauss中,将return语句改为:

        return C/np.exp(exponente)
    

    当您编写np.array([C/(np.exp(exponente))]) 时,您将表达式C/np.exp(exponente)(可能是一个形状为(3,) 的数组)包装在一个形状为(1, 3) 的二维数组中。这不是curve_fit 期望的函数形状。

    【讨论】:

      猜你喜欢
      • 2018-11-04
      • 1970-01-01
      • 2020-05-18
      • 2020-05-05
      • 2016-11-29
      • 2020-07-07
      • 2019-02-12
      • 2020-06-12
      • 2020-07-12
      相关资源
      最近更新 更多