错误的多项式回归图

时间:2016-12-08 15:44:46

标签: python scikit-learn

我正在尝试对数据使用线性和多项式回归。

[[UIApplication sharedApplication] delegate]

使用上面的代码,我收到了这张图片:

enter image description here

但正如你所看到的,多项式回归是不正确的。

我尝试了不同的方法(不使用import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model, cross_validation from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import make_pipeline def f(x): return np.sin(2 * np.pi * x) x = np.random.uniform(0, 1, size=100)[:, np.newaxis] y = f(x) + np.random.normal(scale=0.3, size=100)[:, np.newaxis] x_train, x_test, y_train, y_test = cross_validation.train_test_split(x, y, test_size=0.5, random_state=0) poly_model = make_pipeline(PolynomialFeatures(degree=2), linear_model.LinearRegression()) poly_model.fit(x_train, y_train) linear_model_1 = linear_model.LinearRegression() linear_model_1.fit(x_train, y_train) fig = plt.figure() ax = plt.axes() ax.set(xlabel='X', ylabel='Y', title='X vs Y') ax.scatter(x,y, alpha=0.5, cmap='viridis') ax.plot(x_test, linear_model_1.predict(x_test), color='green', label='linear') ax.plot(x_test, poly_model.predict(x_test), color='red', label='poly') ax.legend() 等),但没有成功。

2 个答案:

答案 0 :(得分:2)

如果我已正确理解您,只需在$contentBoxPrevious.removeClass('active-text'); 中添加一个排序,然后再将其传递给x_test函数,并将多项式的次数增加到3:

predict()

poly_model = make_pipeline(PolynomialFeatures(degree=3), linear_model.LinearRegression())

通过这些调整,我得到以下情节: enter image description here

答案 1 :(得分:0)

1)你可以两次调用情节,它会在现有情节中添加新线。例如:

ax.plot(x_test, model1.predict(x_test), color='red', linewidth=2)
ax.plot(x_test, model2.predict(x_test), color='green', linewidth=2)

在你的情况下,我会这样做:

linear_model = linear_model.LinearRegression(fit_intercept=False)
poly_model = model = Pipeline([('poly', PolynomialFeatures(degree=2)),
                   ('linear', linear_model.LinearRegression(fit_intercept=False))])

linear_model.fit(x_train, y_train)
poly_model.fit(x_train, y_train)

然后:

ax.plot(x_test, linear_model.predict(x_test), color='red', linewidth=2, label='linear')
ax.plot(x_test, poly_model.predict(x_test), color='green', linewidth=2, label='poly')
ax.legend()