python二元函数回归 python二元函数图像在线绘制( 四 )


In [24]: est=smf.ols(formula="chd ~ C(famhist)", data=https://www.04ip.com/post/df).fit()
In [26]: est.summary()
Out[26]:
处理交互作用
随着教育年限(education)的增长,薪酬 (wage) 会增加吗?这种影响对男性和女性而言是一样的吗?
这里的问题就涉及性别与教育年限的交互作用 。
换言之 , 教育年限对薪酬的影响是男女有别的 。
#导入相关模块
In [1]: import pandas as pd
In [2]: import numpy as np
In [4]: import statsmodels.api as sm
#导入数据,存入 dataframe 对象
In [5]: df=pd.read_csv('/Users/xiangzhendong/Downloads/pydatafromweb/wages.csv')
In [6]: df[['Wage','Education','Sex']].tail()
Out[6]:
WageEducationSex
52911.36180
5306.10121
53123.25171
53219.88120
53315.38160
由于性别是一个二分变量,我们可以绘制两条回归线,一条是 sex=0(男性),一条是 sex=1(女性)
#绘制散点图
In [7]: plt.scatter(df.Education,df.Wage, alpha=0.3)
In [9]: plt.xlabel('education')
In [10]: plt.ylabel('wage')
#linspace 的作用是生成从最小到最大的均匀分布的 n 个数
In [17]: education_linspace=np.linspace(df.Education.min(), df.Education.max(),100)
In [12]: import statsmodels.formula.api as smf
In [13]: est=smf.ols(formula='Wage ~ Education + Sex', data=https://www.04ip.com/post/df).fit()
In [18]: plt.plot(education_linspace, est.params[0]+est.params[1]education_linspace+est.params[2]0, 'r')
In [19]: plt.plot(education_linspace, est.params[0]+est.params[1]education_linspace+est.params[2]1, 'g')
以上两条线是平行的 。这是因为分类变量只影响回归线的截距,不影响斜率 。
接下来我们可以为回归模型增加交互项来探索交互效应 。也就是说 , 对于两个类别,回归线的斜率是不一样的 。
In [32]: plt.scatter(df.Education,df.Wage, alpha=0.3)
In [33]: plt.xlabel('education')
In [34]: plt.ylabel('wage')
#使用*代表我们的回归模型中除了交互效应,也包括两个变量的主效应;如果只想看交互效应,可以用:代替,但通常不会只看交互效应
In [35]: est=smf.ols(formula='Wage ~ Sex*Education', data=https://www.04ip.com/post/df).fit()
In [36]: plt.plot(education_linspace, est.params[0]+est.params[1]0+est.params[2]education_linspace+est.params[3]0education_linspace, 'r')
In [37]: plt.plot(education_linspace, est.params[0]+est.params[1]1+est.params[2]education_linspace+est.params[3]1education_linspace, 'g')
参考资料:
DataRobot | Ordinary Least Squares in Python
DataRoboe | Multiple Regression using Statsmodels
AnalyticsVidhya | 7 Types of Regression Techniques you should know!
关于python二元函数回归和python二元函数图像在线绘制的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。