如何找到包含所有变量系数的最终回归模型方程? 有什么方法吗?
给你看一个例子
我向您展示一个使用波士顿房价数据集的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
,这是关于它的官方指南。您可以在指南中找到函数和数据集。
使用print('y = '+str(regressor.coef_[0] )+ ' X + ' + str(regressor.intercept_))
(regressor
是训练模型的线性回归的对象(