gpt4 book ai didi

python - Scipy最小二乘: "func() missing n required positional argument: ' n_ 1', ' n_ 2'..."

转载 作者:行者123 更新时间:2023-12-01 07:07:20 25 4
gpt4 key购买 nike

这是我的代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import least_squares

##################################### Prepare Data #########################################

file = 'https://aegis4048.github.io/downloads/notebooks/sample_data/decline_curve.xlsx'
df = pd.read_excel(file, sheet_name='sheet_1')
df = df[df['Oil Prod. (bopd)'] > 200] # remove bad data points
t = df['Time'][1:].values[: -40]
y = df['Oil Prod. (bopd)'][1:].values[:-40]
x = np.array([i for i in range(len(t))])

############################################################################################


def hyperbolic(x, qi, b, Di):
return qi / (1 + b * Di * x) ** (1 / b)

res_robust = least_squares(hyperbolic, x0=[max(y), 0.1, 0.1], args=(x, y))

我能够使用以下语法轻松地使用 curve_fit 来拟合它:

popt, pcov = curve_fit(hyperbolic, x, y, maxfev=100000, p0=[max(y), 0.1, 0.1])

但是当我尝试使用 least_squares 拟合数据时,我收到以下错误消息:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-5ee2dcc8876d> in <module>()
20 return qi / (1 + b * Di * x) ** (1 / b)
21
---> 22 res_robust = least_squares(hyperbolic, x0=[max(y), 0.1, 0.1], args=(x, y,))

C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\_lsq\least_squares.py in least_squares(fun, x0, jac, bounds, method, ftol, xtol, gtol, x_scale, loss, f_scale, diff_step, tr_solver, tr_options, jac_sparsity, max_nfev, verbose, args, kwargs)
797 x0 = make_strictly_feasible(x0, lb, ub)
798
--> 799 f0 = fun_wrapped(x0)
800
801 if f0.ndim != 1:

C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\_lsq\least_squares.py in fun_wrapped(x)
792
793 def fun_wrapped(x):
--> 794 return np.atleast_1d(fun(x, *args, **kwargs))
795
796 if method == 'trf':

TypeError: hyperbolic() missing 1 required positional argument: 'Di'

我不明白 curve_fitleast_squares 之间的操作差异。有人能给我一个适用于 least_squares 的工作代码吗?

最佳答案

根据 least_squares 文档,您的 fun 应该具有签名:

fun(x, *args, **kwargs)

换句话说,它正在尝试做:

hyperbolic(x0, x, y)     # 3 arguments

x 与形状中的 x0 初始值匹配; (x,y) 来自 args 参数。

对于curve_fit,期望是

ydata = f(xdata, *params)

所以就这样调用它

hyperbolic(x, p0[0], p0[1], p0[2])  # line up with
#hyperbolic(x, qi, b, Di)

您的hyperbolic 签名与curve_fit 调用匹配,但与least_squares 调用不匹配。

关于python - Scipy最小二乘: "func() missing n required positional argument: ' n_ 1', ' n_ 2'...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58382974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com