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

Am I correctly writing code for curve fitting models? The line is way off for every model except for linear regression

我对 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)

有了这些,我从你的代码中得到了很好的情节。