作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的代码:
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_fit
和 least_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/
我是一名优秀的程序员,十分优秀!