【问题标题】:Polynomial Regression Curves in PythonPython中的多项式回归曲线
【发布时间】:2021-01-28 02:19:36
【问题描述】:

我正在尝试为我的数据创建一条回归曲线,角度为 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


【解决方案1】:

在您的绘图中,您只需使用直线从点到点绘制(其中您的 y 值是您的 polyfit 函数的近似 y)。

我会跳过 polyfit 函数(因为你有你感兴趣的所有 y 值),只需使用来自 scipy 的 BSplines 函数 make_interp_spline 插入 data['input']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)

试试这个,然后根据您的数据进行调整! :)

【讨论】:

  • 嗨!非常感谢,但这似乎不起作用。我正在尝试使用 2 阶多项式基函数创建回归曲线。 BSpline 函数只是给我一个值错误:“期望 x 是一维排序的 array_like。”。我想知道是否有办法使用 sklearn 来做到这一点,但我自己想不通..
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 2016-06-10
    • 1970-01-01
    • 2014-06-13
    • 2017-12-11
    • 2019-02-27
    • 1970-01-01
    相关资源
    最近更新 更多