在 python 中找到最终的回归方程
Finding final regression equation in python
如何找到包含所有变量的系数的最终回归模型方程?有什么方法吗?
举个例子
我向您展示了一个使用波士顿房价数据集的 OLS 示例。
代码:
# load a dataset and regression function
from sklearn import linear_model,datasets
import pandas as pd
# I use boston dataset to show you
full_data = datasets.load_boston()
# get a regressor, fit intercept
reg = linear_model.LinearRegression(fit_intercept=True)
# data is our explanatory, target is our response
reg.fit(full_data['data'],full_data['target'])
# we have 1 intercept and 11 variables' coef
reg.intercept_,reg.coef_
# get the name of features
full_data.feature_names
# append to get a new list
coef = np.append(reg.intercept_,reg.coef_)
feature_names = np.append(['Intercept'], full_data.feature_names)
# output a dataframe contains coefficients you want
pd.DataFrame({"feature_names":feature_names,"coef":coef})
输出:
feature_names coef
0 Intercept 36.459488
1 CRIM -0.108011
2 ZN 0.046420
3 INDUS 0.020559
4 CHAS 2.686734
5 NOX -17.766611
6 RM 3.809865
7 AGE 0.000692
8 DIS -1.475567
9 RAD 0.306049
10 TAX -0.012335
11 PTRATIO -0.952747
12 B 0.009312
13 LSTAT -0.524758
一些建议
您可以使用 dir(object)
查看拟合模型中的内容,例如使用 dir(full_data)
和 dir(reg)
查看实例的属性和方法。
至于sklearn
,这里有一个official guide。您可以在指南中找到函数和数据集。
如何找到包含所有变量的系数的最终回归模型方程?有什么方法吗?
举个例子
我向您展示了一个使用波士顿房价数据集的 OLS 示例。
代码:
# load a dataset and regression function
from sklearn import linear_model,datasets
import pandas as pd
# I use boston dataset to show you
full_data = datasets.load_boston()
# get a regressor, fit intercept
reg = linear_model.LinearRegression(fit_intercept=True)
# data is our explanatory, target is our response
reg.fit(full_data['data'],full_data['target'])
# we have 1 intercept and 11 variables' coef
reg.intercept_,reg.coef_
# get the name of features
full_data.feature_names
# append to get a new list
coef = np.append(reg.intercept_,reg.coef_)
feature_names = np.append(['Intercept'], full_data.feature_names)
# output a dataframe contains coefficients you want
pd.DataFrame({"feature_names":feature_names,"coef":coef})
输出:
feature_names coef
0 Intercept 36.459488
1 CRIM -0.108011
2 ZN 0.046420
3 INDUS 0.020559
4 CHAS 2.686734
5 NOX -17.766611
6 RM 3.809865
7 AGE 0.000692
8 DIS -1.475567
9 RAD 0.306049
10 TAX -0.012335
11 PTRATIO -0.952747
12 B 0.009312
13 LSTAT -0.524758
一些建议
您可以使用 dir(object)
查看拟合模型中的内容,例如使用 dir(full_data)
和 dir(reg)
查看实例的属性和方法。
至于sklearn
,这里有一个official guide。您可以在指南中找到函数和数据集。