我是否正确编写了曲线拟合模型的代码?除线性回归外,每个模型的线都偏离了



我对python编码很陌生,可以使用一些支持来回答这个问题。我为这个问题编写了代码,但我的模型看起来不正确。

下面是一个问题:

优化 - 曲线拟合给定 16 对价格(作为因变量)和 相应的需求(作为自变量),使用曲线拟合工具估计最佳拟合 线性、指数、对数和幂曲线。

价格需求 127 3420 134 3400 136 3250 139 3410 140 3190 141 3250 148 2860 149 2830 151 3160 154 2820 155 2780 157 2900 159 2810 167 2580 168 2520 171 2430

下面是我的代码:

from pylab import *
from numpy import *
from numpy.random import *
from scipy.optimize import *
# linear regression
#called in curve fitting model
def linreg(x,a,b):
return a*x+b
# data
x = [3420, 3400, 3250, 3410, 3190, 3250, 2860, 2830, 3160, 2820, 2780, 2900, 2810, 2580, 2520, 2430]
x = np.asarray(x, dtype=np.float64)
y = [127, 134, 136 ,139, 140, 141, 148, 149, 151, 154, 155, 157, 159, 167, 168, 171]
y = np.asarray(y, dtype=np.float64)
#liner regression
# curve fitting
attributes,variances = curve_fit(linreg,x,y)
# estimated y
y_modeled = x*attributes[0]+attributes[1]
# plot true and modeled results
plot(x,y,'ob',markersize=2)
plot(x,y_modeled,'-r',linewidth=1)
show()
# exponential regression
#called in curve fitting model
def expon(x, a, b, c):
return a * np.exp(-b * x) + c
#exponential
# curve fitting
attributes,variances = curve_fit(expon,x,y)
# estimated y
y_modeled = x*attributes[0]+attributes[1]
# plot true and modeled results
plot(x,y,'ob',markersize=2)
plot(x,y_modeled,'-r',linewidth=1)
show()

# logarithmic function
def logar(x, p1,p2):
return p1*np.log(x)+p2
#logarithmic
# curve fitting
attributes,variances = curve_fit(logar,x,y)
# estimated y
y_modeled = x*attributes[0]+attributes[1]
# plot true and modeled results
plot(x,y,'ob',markersize=2)
plot(x,y_modeled,'-r',linewidth=1)
show()
#power curve function? MAybe? 
def powerlaw(x,a,b):
return a*(x**b)
#power curves
# curve fitting
attributes,variances = curve_fit(powerlaw,x,y)
# estimated y
y_modeled = x*attributes[0]+attributes[1]
# plot true and modeled results
plot(x,y,'ob',markersize=2)
plot(x,y_modeled,'-r',linewidth=1)
show()

当我运行线性回归模型时,线拟合数据。但是,每当我运行其他曲线拟合选项时,线都远远高于数据点。它根本不适合数据。

谢谢!任何帮助将不胜感激。我们的助教正在罢工,所以我没有人可以提供帮助。

您没有正确调用模型。试试这些,它们的形式是"function(x, pointer_to_parameters)">

y_modeled = linreg(x, *attributes)
y_modeled = expon(x, *attributes)
y_modeled = logar(x, *attributes)
y_modeled = powerlaw(x, *attributes)

有了这些,我从您的代码中获得了出色的情节。

最新更新