TypeError:无法理解

2024-10-08 18:22:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在拟合一条有三个点的非常简单的曲线。使用leastsq方法,遵循所有规则。但我还是犯了个错误。我不明白。有人能帮忙吗。非常感谢

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import leastsq

x = np.array([2.0,30.2,15.0])
y = np.array([45.0,56.2,30.0])

print(x)
print(y)

# model
def t(x,a,b,c):
    return a*x**2 + b*x + c

#residual fucntion
def residual_t(x,y,a,b,c):
    return y-t(x,a,b,c)


#initial parameters
g0 = np.array([0.0,0.0,0.0])

#leastsq method
coeffs, cov = leastsq(residual_t, g0, args=(x,y))
plt.plot(x,t(x,*coeffs),'r')
plt.plot(x,y,'b')
plt.show()

#finding out Rsquared and Radj squared value
absError = residual_t(y,x,*coeffs)
se = np.square(absError) # squared errors
Rsquared = 1.0 - (np.var(absError) / np.var(y))
n = len(x)
k = len(coeffs)
Radj_sq = (1-((1-Rsquared)/(n-1)))/(n-k-1)
print (f'Rsquared value: {Rsquared}   adjusted R saquared value: {Radj_sq}')

TypeError:剩余的\u t()缺少2个必需的位置参数:“b”和“c”

为什么?? coeffs已经是包含a、b、c的最佳it值的数组。系数也显示未定义,剩余系数也显示问题。你能帮我理解一下吗


Tags: importreturnvaluedefasnppltarray
1条回答
网友
1楼 · 发布于 2024-10-08 18:22:52

通过复制粘贴代码(包括*coeffs更改),我可以

1135:~/mypy$ python3 stack58206395.py 
[ 2.  30.2 15. ]
[45.  56.2 30. ]
Traceback (most recent call last):
  File "stack58206395.py", line 24, in <module>
    coeffs, cov = leastsq(residual_t, g0, args=(x,y))
  File "/usr/local/lib/python3.6/dist-packages/scipy/optimize/minpack.py", line 383, in leastsq
    shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
  File "/usr/local/lib/python3.6/dist-packages/scipy/optimize/minpack.py", line 26, in _check_func
    res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
TypeError: residual_t() missing 2 required positional arguments: 'b' and 'c'

也就是说,在leastsq调用中使用residual_t是错误的

如果我加上

residual_t(g0, x, y)

g0定义之后,我得到了相同的错误:

1136:~/mypy$ python3 stack58206395.py 
[ 2.  30.2 15. ]
[45.  56.2 30. ]
Traceback (most recent call last):
  File "stack58206395.py", line 23, in <module>
    residual_t(g0, x, y)
TypeError: residual_t() missing 2 required positional arguments: 'b' and 'c'

所以您需要定义residual_t来处理这样的调用。我不想猜测你到底想要什么,所以我把问题留给你解决

请记住,residual_t将用x0调用,并用args元组拼接。这是scipy.optimize函数的典型用法。必要时检查文件

编辑

将函数定义为:

def residual_t(abc, x, y):
    a,b,c = abc
    return y-t(x,a,b,c)

运行无错误

相关问题 更多 >

    热门问题