大家好,我想在python中使用曲线拟合进行非线性回归 这是我的代码:
#fit a fourth degree polynomial to the economic data
from numpy import arange
from scipy.optimize import curve_fit
from matplotlib import pyplot
import math
x = [17.47,20.71,21.08,18.08,17.12,14.16,14.06,12.44,11.86,11.19,10.65]
y = [5,35,65,95,125,155,185,215,245,275,305]
# define the true objective function
def objective(x, a, b, c, d, e):
return ((a)-((b)*(x/3-5)))+((c)*(x/305)**2)-((d)*(math.log(305))-math.log(x))+((e)*(math.log(305)-(math.log(x))**2))
popt, _ = curve_fit(objective, x, y)
# summarize the parameter values
a, b, c, d, e = popt
# plot input vs output
pyplot.scatter(x, y)
# define a sequence of inputs between the smallest and largest known inputs
x_line = arange(min(x), max(x), 1)
# calculate the output for the range
y_line = objective(x_line, a, b, c, d, e)
# create a line plot for the mapping function
pyplot.plot(x_line, y_line, '--', color='red')
pyplot.show()
这是我的错误:
回溯(最近一次呼叫最后一次): 文件“C:\Users\Fahmi\PycharmProjects\pythonProject\main.py”,第16行,在 popt,曲线拟合(目标,x,y) 文件“C:\Users\Fahmi\PycharmProjects\pythonProject\venv\lib\site packages\scipy\optimize\minpack.py”,第784行,曲线拟合 res=leastsq(func,p0,Dfun=jac,满输出=1,**kwargs) 文件“C:\Users\Fahmi\PycharmProjects\pythonProject\venv\lib\site packages\scipy\optimize\minpack.py”,第410行,在leastsq中 shape,dtype=\u check\u func('leastsq','func',func,x0,args,n) 文件“C:\Users\Fahmi\PycharmProjects\pythonProject\venv\lib\site packages\scipy\optimize\minpack.py”,第24行,在检查功能中 res=至少1d(thefunc(((x0[:numput],)+args))) 文件“C:\Users\Fahmi\PycharmProjects\pythonProject\venv\lib\site packages\scipy\optimize\minpack.py”,第484行,按func\U包装 返回函数(扩展数据,参数)-ydata 文件“C:\Users\Fahmi\PycharmProjects\pythonProject\main.py”,第13行,在objective中 返回((a)-(b)(x/3-5))+((c)(x/305)**2)-(d)(math.log(305))-math.log(x))+((e)(math.log(305)-(math.log(x))**2)) TypeError:只有大小为1的数组才能转换为Python标量
谢谢你
这是一个已知的数学库问题。只要使用numpy,您的问题就会得到解决,因为numpy函数支持标量和数组
相关问题 更多 >
编程相关推荐