【问题标题】:Scikit learn; cannot create plot for polynomial regression correctlyScikit 学习;无法正确创建多项式回归图
【发布时间】:2018-10-12 03:33:18
【问题描述】:

我刚开始学习多项式回归。我试图为多项式回归创建图,但图是错误的。

我的代码是这样的

#Linear regression
from sklearn import linear_model
clf = linear_model.LinearRegression()


x = data.loc[:, ['col1']]
y = data.loc[:, ['col2']]

clf.fit(x, y)

plt.scatter(x, y)
plt.plot(x, clf.predict(x))
plt.show()

此代码用于线性回归模型,图是这样的。

多项式回归的代码在这里

from sklearn.preprocessing import PolynomialFeatures

poly_reg = PolynomialFeatures(degree=2)
poly_x = poly_reg.fit_transform(x)

clf.fit(poly_x, y)

plt.scatter(x, y)
plt.plot(x, clf.predict(poly_x))

剧情是这样错的。

我刚开始学习它,我只是尝试复制一些教程的方式,所以我对此的理解仍然很糟糕。我该如何解决这个情节,并且我希望有很好的资源来理解这个概念。

【问题讨论】:

  • 请对X数据排序后再试
  • 你的意思是按 x 排序值?

标签: python scikit-learn regression


【解决方案1】:

尝试使用pipeline进行拟合和预测

示例:

poly_model = make_pipeline(PolynomialFeatures(7),
                       LinearRegression())

rng = np.random.RandomState(1)
x = 10 * rng.rand(50)
y = np.sin(x) + 0.1 * rng.randn(50)
xfit = np.linspace(0, 10, 1000)

poly_model.fit(x.reshape(-1,1), y)
yfit = poly_model.predict(xfit.reshape(-1,1))

plt.scatter(x, y)
plt.plot(xfit, yfit)

通过上面的例子,你会明白,如果你有一个单独的列,使用.reshape(-1,1)是非常重要的。

看看这是否有助于你理解...

【讨论】:

  • 抱歉,我看不到您的代码如何适应我的代码。没有reshape有什么问题?
  • @dude OP 的数据形状正确。不需要这个。
  • 对不起 OP 是什么意思?另外请告诉我我的情节或方式有什么问题?
【解决方案2】:

需要先按照X中的值对X和y中的值进行排序。

# This is your data
x = data.loc[:, ['col1']]
y = data.loc[:, ['col2']]

# This is what you need to do.
# argsort() will return the indices of the sorting order
inds = x.values.ravel().argsort()    # Here I am assuming that x has single feature     
x = x.values.ravel()[inds].reshape(-1,1)
y = y.values[inds]

# Then continue your code.
poly_reg = PolynomialFeatures(degree=2)
poly_x = poly_reg.fit_transform(x)

clf.fit(poly_x, y)

plt.scatter(x, y)
plt.plot(x, clf.predict(poly_x))
plt.show()

【讨论】:

  • 感谢您让答案更清楚,但 'DataFrame' 对象没有属性 'ravel' 发生此错误。 x 有一列。
  • 我将数据框更改为系列对象,我会尝试。
  • 现在 y = y[inds] 这行会导致错误。 ...不在索引中'也许问题是 x 和 y 的索引不是数字
  • @dude 我编辑了答案。我使用 .values 将数据帧转换为 numpy 数组。请检查
  • 'DataFrame' 对象没有属性 'ravel' 我再次复制了您的答案,但此错误发生在 'inds = x.ravel().argsort()'
猜你喜欢
  • 2020-07-04
  • 2021-05-25
  • 2019-07-18
  • 2015-08-05
  • 2016-03-26
  • 2018-03-16
  • 2017-12-11
  • 2018-08-17
  • 2019-02-07
相关资源
最近更新 更多