多项式回归曲线

问题描述 投票:0回答:3

我正在尝试为我的数据创建一条 2 度的回归曲线。当我创建图表时,我得到了一个有趣的锯齿状的东西:

但我想将我的数据建模为实际曲线,这看起来像散点图的连接版本。

有什么建议/更好的方法吗?

degree = 2
p = np.poly1d(np.polyfit(data['input'],y, degree))
plt.plot(data['input'], p(data['input']), c='r',linestyle='-')
plt.scatter(data['input'], p(data['input']), c='b')

这里,data['input'] 是一个与 y 维度相同的列向量。

编辑:我也尝试过这样的:

X, y = np.array(data['input']).reshape(-1,1), np.array(data['output'])
lin_reg=LinearRegression(fit_intercept=False)
lin_reg.fit(X,y)

poly_reg=PolynomialFeatures(degree=2)
X_poly=poly_reg.fit_transform(X)
poly_reg.fit(X_poly,y)
lin_reg2=LinearRegression(fit_intercept=False)
lin_reg2.fit(X_poly,y)

X_grid=np.arange(min(X),max(X),0.1)
X_grid=X_grid.reshape((len(X_grid),1))
plt.scatter(X,y,color='red')
plt.plot(X,lin_reg2.predict(poly_reg.fit_transform(X)),color='blue')
plt.show()

这给了我这张图。

散点图是我的数据,蓝色锯齿形是对数据进行建模的二次曲线。帮忙吗?

python matplotlib regression curve-fitting polynomials
3个回答
0
投票

在你的图中,你只需用直线从一个点到另一个点进行绘制(其中你的y值是你的polyfit函数的近似y)。

我会跳过polyfit函数(因为你有你感兴趣的所有y值),只需使用来自

data['input']
的BSplines函数
y
插入
make_interp_spline
scipy
,并用你感兴趣的范围绘制新的y值x.

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as interp

从点到点绘制(之字形)

x = np.array([1, 2, 3, 4])
y = np.array([75, 0, 25, 100])
plt.plot(x, y)

插值点

x_new = np.linspace(1, 4, 300)
a_BSpline = interp.make_interp_spline(x, y)
y_new = a_BSpline(x_new)
plt.plot(x_new, y_new)

尝试一下,然后根据您的数据进行调整! :)


0
投票
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

#improve degree = 3
p_reg = PolynomialFeatures(degree = 3)
X_poly = p_reg.fit_transform(X)

#again create new linear regression obj
reg2 = LinearRegression()
reg2.fit(X_poly,y)
plt.scatter(X, y, color = 'b')
plt.xlabel('Level')
plt.ylabel('Salary')
plt.title("Truth or Bluff")

# predicted values
plt.plot(X, reg2.predict(X_poly), color='r')
plt.show()

With Degree 3

With Degree 4


0
投票

因为你没有向我们展示你的数据,我假设你的自变量不是单调的。

下面是我的代码

  1. 计算两个数据向量,其中 y = y(x)x 不是单调的,然后在上图左侧绘制 x vs y=p(x) 的散点图和线图) 其中 y 是根据最佳拟合多项式计算得出的(我的方法比你的更简单)。
  2. 上图右侧,再次绘制相同的散点图,对x → xs进行排序,最后绘制xs vs y=p(xs)的线图。
© www.soinside.com 2019 - 2024. All rights reserved.