我对用 python 编码很陌生,可以在回答这个问题时使用一些支持。我为这个问题编写了代码,但我的模型看起来不正确。
下面是问题:
优化 - 曲线拟合 给定 16 对价格(作为因变量)和相应的需求(作为自变量),使用曲线拟合工具估计最佳拟合线性、指数、对数和幂曲线。
价格 需求 127 3420 134 3400 136 3250 139 3410 140 3190 141 3250 148 2860 149 2830 151 3160 154 2820 7 10 2 5 10 2 7 8 1 0 1 0
下面是我的代码:
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()
当我运行线性回归模型时,该线拟合数据。但是,每当我运行其他曲线拟合选项时,线都在数据点上方。它根本不符合数据。
谢谢!任何帮助将不胜感激。我们的助教正在罢工,所以我没有人可以提供帮助。
catspeake
相关分类