【问题标题】:Scikit-Learn LinearRegression: Calculate predictions from coef and intercept [closed]Scikit-Learn LinearRegression:根据 coef 和截距计算预测 [关闭]
【发布时间】:2021-11-22 05:53:40
【问题描述】:

在我训练了一个 LinearRegression 模型后,我如何将 coefintercept 与我的 predict 结果关联起来?

我正在使用的数据集: https://github.com/selva86/datasets/blob/master/BostonHousing.csv

我的代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
housing_dataset = pd.read_csv("BostonHousing.csv")
X = housing_dataset.drop(["medv"], axis = 1)
y = housing_dataset.filter(["medv"], axis = 1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
house_predictor = LinearRegression()
house_predictor.fit(X_train, y_train)
y_pred = house_predictor.predict(X_test)

然后我检查了coefintercept_

coef = house_predictor.coef_
intercept = house_predictor.intercept_
data = [0] * len(X_test)
for i in range(0,12):
    t = X_test.iloc[:,i] * coef[0][i]
    data += t
data += intercept

我的理解是coef是指每列对价格的影响因子

这意味着:medv = crim*coef[0] + zn*coef[1]...lstat*coef[12] + intercept

然后我将所有三列放在一起,作为测试数据集:

comparison_df = pd.DataFrame( data=[y_test.medv.values,[ x[0] for x in y_pred],
                                    data.values
                                   
                                   ]
                              
                            ).T 

comparison_df.columns = ["Actual", "Predict", "calc"]

我希望字段“预测”与“计算”相同

但这就是我得到的

Actual  Predict calc
0   23.6    28.996724   33.594209
1   32.4    36.025565   37.820822
2   13.6    14.816944   24.006830
3   22.8    25.031979   27.839293
4   16.1    18.769880   27.552908
... ... ... ...
97  17.9    -0.164237   17.315363
98  9.6 13.684867   22.864581
99  17.2    16.183597   26.975483
100 22.5    22.276220   28.816449
101 21.4    24.479024   29.025652

这与准确性相差太远了。

有人可以点亮吗?

【问题讨论】:

  • 您的方法是正确的,代码中只有一个小错误,因为您使用X_test 的前12 列计算预测,但X_test 有13 列。
  • 对于 Flavia 的观点,请记住 range 排除上限。 (而且下限默认为 0,所以range(X_test.shape[1]) 可以正常工作并且更清晰一些。)

标签: python machine-learning scikit-learn linear-regression


【解决方案1】:

感谢@Flavia Giammarino 和@Ben Reiniger!是的,在我将范围从 0-13 更改之后!

总结:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 2020-09-30
    • 2016-02-19
    • 2018-02-22
    • 2015-12-19
    • 2018-01-09
    • 2015-03-11
    • 2012-02-15
    相关资源
    最近更新 更多