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

2024-04-20 12:44:41 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在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的幂),等等。例如,如何从下面得到最适合的曲线?

摘自克里斯托弗主教的“模式识别和机器学习”,第7页:

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


Tags: infromself列表formodelmatplotlib绘制
1条回答
网友
1楼 · 发布于 2024-04-20 12:44:41

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 = numpy.polyfit(x,y,3),而不是coeffs = mpf(...

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

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.

相关问题 更多 >