python - python中的多元(多项式)最佳拟合曲线?

标签 python matplotlib machine-learning regression scatter-plot

如何在 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 的“模式识别和机器学习”,第 7 页:

Extracted from Christopher Bishops's "Pattern Recognition and Machine Learning", p.7

最佳答案

接受 this question 的答案 提供 a small multi poly fit library 这将完全满足您使用 numpy 的需要,并且您可以将结果插入到绘图中,如下所述。

您只需将 x 和 y 点数组以及所需的拟合度(顺序)传入 multipolyfit。这将返回您可以使用 numpy 的 polyval 进行绘图的系数。

注意:以下代码已被修改为进行多元拟合,但绘图图像是早期非多元答案的一部分。

import numpy
import matplotlib.pyplot as plt
import multipolyfit as mpf

data = [[1,1],[4,3],[8,3],[11,4],[10,7],[15,11],[16,12]]
x, y = zip(*data)
plt.plot(x, y, 'kx')

stacked_x = numpy.array([x,x+1,x-1])
coeffs = mpf(stacked_x, y, deg) 
x2 = numpy.arange(min(x)-1, max(x)+1, .01) #use more points for a smoother plot
y2 = numpy.polyval(coeffs, x2) #Evaluates the polynomial for each x2 value
plt.plot(x2, y2, label="deg=3")

enter image description here


注意:这是前面答案的一部分,如果您没有多变量数据,它仍然是相关的。代替 coeffs = mpf(...,使用 coeffs = numpy.polyfit(x,y,3)

对于非多元数据集,最简单的方法可能是使用 numpy 的 polyfit :

numpy.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)

Least squares polynomial fit.

Fit a polynomial p(x) = p[0] * x**deg + ... + p[deg] of degree deg to points (x, y). Returns a vector of coefficients p that minimises the squared error.

关于python - python中的多元(多项式)最佳拟合曲线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11856206/

相关文章:

python - 添加数据标签 - matplotlib 条形图

python - 为什么 `len(l) != 0` 在 CPython 中比 `bool(l)` 快?

javascript - Ajax 请求不返回所有 JSON - 无法加载资源 : the server responded with a status of 409 (Conflict)

python - 如何使用 BeautifulSoup 检查关闭标签的总数?

python - 更新散点图的标记大小

javascript - 拖动后获取点信息

.jpeg 文件的 Python 导入文件夹

matlab - 编码分类树...如何存储?

python - 保持成对线的内存有效方式(字符串匹配)

python - 光GBM : validation AUC score during model fit differs from manual testing AUC score for same test set