首页 > 解决方案 > 类型错误:无法理解

问题描述

我正在拟合一条非常简单的三点曲线。使用 minimumsq 方法,遵循所有规则。但我仍然收到错误。我无法理解。任何人都可以帮忙。太感谢了

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}')

类型错误:residual_t() 缺少 2 个必需的位置参数:“b”和“c”

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

标签: pythonnumpyscipyleast-squares

解决方案


通过复制粘贴您的代码(包括*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'

那就是错误是在使用residual_tleastsq调用。

如果我添加

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)

运行没有错误。


推荐阅读