3

我被困在解决这个问题两天了。我有一些数据点放入 ascatter plot并得到这个:

在此处输入图像描述

这很好,但现在我还想添加一条回归线,所以我从 sklearn 中查看了这个示例并将代码更改为

import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score

degrees = [3, 4, 5]
X = combined[['WPI score']]
y = combined[['CPI score']]

plt.figure(figsize=(14, 5))
for i in range(len(degrees)):
    ax = plt.subplot(1, len(degrees), i + 1)
    plt.setp(ax, xticks=(), yticks=())

    polynomial_features = PolynomialFeatures(degree=degrees[i], include_bias=False)
    linear_regression = LinearRegression()
    pipeline = Pipeline([("polynomial_features", polynomial_features), ("linear_regression", linear_regression)])
    pipeline.fit(X, y)

    # Evaluate the models using crossvalidation
    scores = cross_val_score(pipeline, X, y, scoring="neg_mean_squared_error", cv=10)

    X_test = X #np.linspace(0, 1, len(combined))
    plt.plot(X, pipeline.predict(X_test), label="Model")
    plt.scatter(X, y, label="CPI-WPI")
    plt.xlabel("X")
    plt.ylabel("y")
    plt.legend(loc="best")
    plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(degrees[i], -scores.mean(), scores.std()))
plt.savefig(pic_path + 'multi.png', bbox_inches='tight')
plt.show()

它具有以下输出:

在此处输入图像描述

请注意Xy都是DataFramessize (151, 1)。如有必要,我也可以发布 X 和 y 的内容。

我想要的是一条漂亮的平滑线,但我似乎无法弄清楚如何做到这一点。

[编辑]

这里的问题是:如何获得一条平滑、弯曲的多项式线,而不是看似随机模式的多条多项式线。

[编辑 2]

问题是,当我使用linspace这样的:

X_test = np.linspace(1, 4, 151)
X_test = X_test[:, np.newaxis]

我得到一个更随机的模式:

在此处输入图像描述

4

1 回答 1

1

诀窍是设置如下代码:

X_test = np.linspace(min(X['GPI score']), max(X['GPI score']), X.shape[0])
X_test = X_test[:, np.newaxis]
plt.plot(X_test, pipeline.predict(X_test), label="Model")

这会产生以下结果(更好的单条平滑线)

1 到 6 级型号

于 2016-11-15T19:04:51.783 回答