我正在尝试为一组数据找到最好的多项式。它计算每个多项式拟合一定次数的AIC,然后选择AIC最低的多项式。据我所知(我可能错了),我发现的最低AIC值是最合适的。
在这里,我定义了我的多项式:
def p2(xData,a0,a1,a2):
return a0 + a1 * xData + a2 * xData**2
def p3(xData,a0,a1,a2,a3):
return a0 + a1 * xData + a2 * xData**2 + a3 * xData**3
def p4(xData,a0,a1,a2,a3,a4):
return a0 + a1 * xData + a2 * xData**2 + a3 * xData**3 + a4 * xData**4我的计算AIC的函数:
def compute_AIC(yData,model,variables):
residual=yData-model
SSE=np.sum(residual**2)
return 2*variables-2*np.log(SSE)我的代码将多项式拟合到我的数据中,并选择最好的:
def polynom_best_fit(xData,yData):
print('Assessing if the best fit is higher order..')
AICS=[]
for i in [2,3,4]:
params=[]
params=poly.polyfit(xData,yData,i)
print(params)
if len(params) == 3:
model_p2=p2(xData,*params)
AICS.append(compute_AIC(yData,model_p2,3))
if len(params) == 4:
model_p3=p3(xData,*params)
AICS.append(compute_AIC(yData,model_p3,4))
if len(params) == 5:
model_p4=p4(xData,*params)
AICS.append(compute_AIC(yData,model_p4,5))
else:
continue
print(AICS)
best=np.where(AICS==min(AICS))
best_model=[]
for i in best:
if np.where(AICS==min(AICS))[0][0] == 0:
print('Second degree best fit')
print('with AIC =', min(AICS))
plt.plot(xData,model_p2,color='red')
plt.scatter(xData,yData)
plt.show()
return min(AICS)
if np.where(AICS==min(AICS))[0][0] == 1:
print('Third degree best fit')
print('with AIC =', min(AICS))
return min(AICS)
if np.where(AICS==min(AICS))[0][0] == 2:
print('Fourth degree best fit')
print('with AIC =', min(AICS))
return min(AICS)
else:
print('Error')但是,当我使用需要调整的代码执行此操作时,我会得到:

它的AIC值低得令人难以置信。
对于分段线性回归显然看起来最适合的数据集,该函数创建了一个多项式,该多项式的AIC值低于我的分段线性回归,后者的R平方超过0.99,但AIC约为12。

这不能通过健全性检查,所以我一定是做错了什么。我想也许我对多项式的定义或者我定义计算AIC的函数的方式是错误的,或者仅仅是我对AIC告诉我关于最佳拟合的理解是错误的。
也可能的情况是,即使我的分段回归往往具有非常好的R平方值,它们也有大量的参数(断点1、断点2、slope1、slope2、slope3、offset1、offset2、offset3 --生成8个参数或变量),这些参数可能使多项式胜出,但我仍然怀疑我的代码是否说出了真相。
发布于 2019-08-19 18:30:43
从图的连接点到问题,所表示的函数y(x)看起来像是由三个分段组成的分段函数。
文中给出了一种非常简单的方法(无需猜测初值,无需迭代演算):https://fr.scribd.com/document/380941024/Regression-par-morceaux-Piecewise-Regression-pdf
这种分段线性函数的情况见29-30页。这篇论文是用法语写的。相关页面的翻译如下:


由于没有给出数据,多亏了OP发布的数据扫描,才获得了近似数据。
结果是:

有关信息,请访问:
由于分段函数是非线性函数(甚至由线性段组成),因此全局回归的线性化基于积分方程:

有关更多说明,请参阅参考文档。
https://stackoverflow.com/questions/56603201
复制相似问题