如何在python中计算一条最佳拟合线,然后在matplotlib中将其绘制在散点图上?
我使用普通的最小二乘回归计算线性最佳拟合线,如下所示:
from sklearn import linear_model
clf = linear_model.LinearRegression()
x = [[t.x1,t.x2,t.x3,t.x4,t.x5] for t in self.trainingTexts]
y = [t.human_rating for t in self.trainingTexts]
clf.fit(x,y)
regress_coefs = clf.coef_
regress_intercept = clf.intercept_
这是多变量的(每种情况都有许多x值)。因此,X是列表的列表,而y是单个列表。例如:
x = [[1,2,3,4,5], [2,2,4,4,5], [2,2,4,4,1]]
y = [1,2,3,4,5]
但是我如何用高阶多项式函数来做这件事。例如,不只是线性(x是M=1的幂),还有二项式(x是M=2的幂)、二次(x是M=4的幂)等等。例如,如何从以下曲线中获得最佳拟合曲线?
摘自Christopher Bishops的"Pattern Recognition and Machine Learning",第7页:
发布于 2021-03-26 16:17:48
稍微脱离了上下文,因为结果函数不是多项式,但可能仍然很有趣。多项式拟合的一个主要问题是Runge's phenomenon:阶数越高,发生的振荡就越明显。这也不是刚刚构建的,但它会回来咬你的。
作为补救措施,我不久前创建了smoothfit。它解决了适当的最小二乘问题,并给出了很好的结果,例如:
import numpy as np
import matplotlib.pyplot as plt
import smoothfit
x = [1, 4, 8, 11, 10, 15, 16]
y = [1, 3, 3, 4, 7, 11, 12]
a = 0.0
b = 17.0
plt.plot(x, y, 'kx')
lmbda = 3.0 # controls the smoothness
n = 100
u = smoothfit.fit1d(x, y, a, b, n, lmbda)
x = np.linspace(a, b, n)
vals = [u(xx) for xx in x]
plt.plot(x, vals, "-")
plt.show()
https://stackoverflow.com/questions/11856206
复制相似问题