【问题标题】:Matplotlib polynomial regression — too many lines showingMatplotlib 多项式回归 - 显示的线条过多
【发布时间】:2021-03-11 06:53:57
【问题描述】:

这是我使用的代码——然而,对于下图,所有这些蜘蛛网状的线条不断弹出,我想让它们消失。有什么建议?我只想要一条弯曲的 3 次多项式线,它可以在没有蜘蛛网的情况下适当地拟合数据。

df = pd.read_csv('poly_data.csv', delimiter = ' ', names = ['x', 'y'])
x = df['x'].to_numpy()
y = df['y'].to_numpy()


model = LinearRegression()
poly = PolynomialFeatures(3)
x_poly = poly.fit_transform(x.reshape(-1, 1))
model.fit(x_poly, y.reshape(-1, 1))[![enter image description here][1]][1]
y_pred = model.predict(x_poly)

plt.scatter(x, y)
plt.scatter(x, y_pred)
plt.plot(x, model.predict(x_poly), label = '3rd order')
plt.title('Polynomial Regression')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

【问题讨论】:

    标签: python matplotlib scikit-learn linear-regression polynomials


    【解决方案1】:

    你看到蜘蛛网是因为你的x值没有排序,看代码,你可以先对你的data.frame进行排序,比如你的data.frame是这样的:

    import pandas as pd
    import matplotlib.pyplot as plt
    from sklearn.linear_model import LinearRegression
    from sklearn.preprocessing import PolynomialFeatures
    
    df = pd.DataFrame({'x':np.random.uniform(-5,5,20)})
    df['y'] = 5+ 2*df['x'] - 7*df['x']**2 +2*df['x']**3 + np.random.normal(20)
    

    排序,分配 x 和 y 并拟合,绘图:

    df = df.sort_values('x')
    
    x = df[['x']]
    y = df.sort_values('x')['y']
    
    model = LinearRegression()
    poly = PolynomialFeatures(3)
    x_poly = poly.fit_transform(x)
    model.fit(x_poly,y)
    y_pred = model.predict(x_poly)
    
    plt.scatter(x, y)
    plt.scatter(x, y_pred)
    plt.plot(x, model.predict(x_poly))
    

    或者你定义一个排序的网格线来绘制:

    plt.scatter(x, y)
    plt.scatter(x, y_pred)
    xl = np.linspace(x.min(),x.max(),20)
    plt.plot(xl, model.predict(poly.fit_transform(xl.reshape(-1, 1))))
    

    【讨论】:

      【解决方案2】:

      这是不正确的。排序值会改变回归结果。 它改变了相关性。

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2018-08-27
      • 2020-02-01
      • 2019-01-14
      • 1970-01-01
      • 2023-01-17
      • 2020-05-08
      • 2016-06-10
      • 2021-01-28
      • 1970-01-01
      相关资源
      最近更新 更多