Python sklearn多元回归

2024-06-01 13:37:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我要解决这个问题已经两天了。我有一些数据点放在scatter plot中,然后得到:

enter image description here

这很好,但是现在我还想添加一条回归线,所以我查看了sklearn中的example,并将代码改为

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()

其输出如下:

enter image description here

注意,X和{}都是DataFrames大小(151, 1)。如果需要,我也可以发布X和y的内容。在

我想要的是一条平滑的线条,但我似乎不知道该怎么做。在

[编辑]

这里的问题是:我如何得到一条平滑的曲线,而不是多条看起来随机的多项式曲线。在

[编辑2]

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

^{pr2}$

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

enter image description here


Tags: fromimportlenpipelinepltsklearnscorelinear
1条回答
网友
1楼 · 发布于 2024-06-01 13:37:35

诀窍是设置如下代码:

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")

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

Model with degree 1 to 6

相关问题 更多 >