python - 类型错误:无法理解
问题描述
我正在拟合一条非常简单的三点曲线。使用 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 也显示问题。你能帮我理解吗。
解决方案
通过复制粘贴您的代码(包括*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_t
内leastsq
调用。
如果我添加
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)
运行没有错误。
推荐阅读
- mongodb-query - 使用 $and 命令查询 MongoDB 时出错:db.users.find({$and:[{$text:{$search:"England -UEFA"}},{$text:{$search:"Euro 2016}}] })。数数()
- lua - 为什么这适用于点运算符?
- python - 使参数无效以创建 NamedTuple 的实例
- javascript - 如何将文本字段 1 中的值写入文本字段 2,反之亦然
- rest - gRPC 部分资源更新
- c# - 有没有办法用大量可编写脚本的对象填充列表
- php - 将数据保存到数据库时 Laravel Ajax 500 内部服务器错误
- pyspark - 从 pyspark 读取时,Google Cloud Storage 需要 storage.objects.create 权限
- c - 将入口点更改为PE文件中新添加的shellcode部分后如何恢复主进程?
- java - 限制条件下的过滤列表