目录
简单线性回归
多元线性回归
分类变量转换成虚拟变量
对statsmodels库的整理可以与sklearn库的整理互相参考借鉴
statsmodels库——线性回归模型_我就是一个小怪兽的博客-CSDN博客
from sklearn import linear_model#导入所需要的包
lr=linear_model.LinearRegression()#指定模型
#再fit中指定自变量和响应变量,注意此处使用的是大写X和小写y
#由于sklearn接受的是numpy数组,所以又是需要处理数据,为了将dataframe传入sklearn。
predicted=lr.fit(X=tips['total_bill'].values.reshape(-1,1),y=tips['tip'])
print(predicted.coef_)#通过拟合模型的coef_属性来获得系数
print('----'*6)#输出横线以区分每一个输出
print(predicted.intercept_)#通过拟合模型的intercept_属性来得到截距
print('----'*6)
y_pre=lr.predict(tips['total_bill'][0:2].values.reshape(-1,1))#根据拟合的线性模型得到预测值
print(y_pre)#输出预测值
print(tips['tip'][0:2])#输出实际值进行比较
[0.10502452] ------------------------ 0.9202696135546731 ------------------------ [2.70463616 2.00622312] 0 1.01 1 1.66 Name: tip, dtype: float64
from sklearn import linear_model#导入所需要的包
lr=linear_model.LinearRegression()
predicted=lr.fit(X=tips[['total_bill','size']],y=tips['tip'])#传入多列时用列表传入
print(predicted.coef_)
print('----'*6)
print(predicted.intercept_)
[0.09271334 0.19259779] ------------------------ 0.6689447408125031
由于有sklearn遇到分类变量的时候需要手动创建虚拟变量,使用pandas中的get_dummies函数
import pandas as pd
#创建虚拟变量,其中drop_first参数指定是否删除参考变量
tips_dummy=pd.get_dummies(tips[['total_bill','size','sex','smoker','day','time']],drop_first=False)
print(tips_dummy.head())
total_bill size sex_Male sex_Female smoker_Yes smoker_No day_Thur \ 0 16.99 2 0 1 0 1 0 1 10.34 3 1 0 0 1 0 2 21.01 3 1 0 0 1 0 3 23.68 2 1 0 0 1 0 4 24.59 4 0 1 0 1 0 day_Fri day_Sat day_Sun time_Lunch time_Dinner 0 0 0 1 0 1 1 0 0 1 0 1 2 0 0 1 0 1 3 0 0 1 0 1 4 0 0 1 0 1
from sklearn import linear_model#导入所需要的包
import pandas as pd
#创建虚拟变量,其中drop_first参数指定是否删除参考变量,比如性别分为男女两类,那么系统会选定第一个男为参考变量,删除之后就不会将男这一列转换成虚拟变量
tips_dummy_drop=pd.get_dummies(tips[['total_bill','size','sex','smoker','day','time']],drop_first=True)
print(tips_dummy_drop.head())
lr=linear_model.LinearRegression()
predicted=lr.fit(X=tips_dummy_drop,y=tips['tip'])#传入多列时用列表传入
print(predicted.coef_)
print(predicted.intercept_)
total_bill size sex_Female smoker_No day_Fri day_Sat day_Sun \ 0 16.99 2 1 1 0 0 1 1 10.34 3 0 1 0 0 1 2 21.01 3 0 1 0 0 1 3 23.68 2 0 1 0 0 1 4 24.59 4 1 1 0 0 1 time_Dinner 0 1 1 1 2 1 3 1 4 1 ------------------------ [ 0.09448701 0.175992 0.03244094 0.08640832 0.1622592 0.04080082 0.13677854 -0.0681286 ] ------------------------ 0.590837425951376