我是否正确编写曲线拟合模型的代码?除了线性回归之外,每条模型都有一条线

问题描述 投票:1回答:1

我非常擅长使用p​​ython进行编码,可以使用一些支持来回答这个问题。我写了问题的代码,但我的模型看起来不正确。

以下是问题:

优化 - 曲线拟合给定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()

当我运行线性回归模型时,线条适合数据。但是,每当我运行其他曲线拟合选项到行时,数据点上方就是WAY。它根本不适合数据。

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

python python-2.7 regression curve-fitting exponential
1个回答
1
投票

您没有正确调用模型。试试这些,其形式为“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)

通过这些,我可以从您的代码中获得优秀的图表。

© www.soinside.com 2019 - 2024. All rights reserved.