python回归分析

目录

含定性变量的线性回归

非线性回归 

 

含定性变量的线性回归

# 1.treatment包实现dummy
from patsy.contrasts import Treatment
contrast = Treatment(reference=3).code_without_intercept([1,2,3])
#分类变量有三个属性分别可以用1,2,3表示,参考属性设置为3(表现为0,0)
>> ContrastMatrix(array([[1., 0.],
                      [0., 1.],
                      [0., 0.]]), ['[T.1]', '[T.2]'])
formula='Current_Salary~Education+Begin_Salary+Experience-Age+C(position,Treatment(reference=3))+C(Gender)'
model1=old(formula,data=salary).fit()

#get_dummies实现dummy
dm=pd.get_dummies(salary['position_valuelabel'],prefix='postion_')
salary=salary.join(dm)

from statsmodels.formula.api import ols
formula='Current_Salary~Education+Begin_Salary+Experience-Age+position1+postion2+Gender'
model1=old(formula,data=salary).fit()
#查看类似r的结果
model.summary2()
#qq图
sm.qqplot(model.resid,fit=True,line='45')
plt.show()
#自变量与残差的图
plt.plot(muder['illiteracy'],model.redis,'o')
plt.xlabel('illiteracy')
plt.ylabel('residual')
plt.show()
# 更多图
from statsmodels.graphics.regressionplots import plot_regress_exog
plot_regress_exog(model,1,fig=fig) # 第二个参数指模型中的第几个变量
# 看看fit和real的y在这个变量上的表现
from statsmodels.graphics.regressionplots import plot_fit
plot_fit(model,1) # 第二个参数指模型中的第几个变量
# 拟合曲线置信区间
from statsmodels.graphics.regressionplots import wls_prediction_std
prstd,interval_l,interval_u=wls_prediction_std(model,alpha=0.05)
fig=plt.subplots(figsize(7,4))
plt.plot(x1,y,'o',label='data')
plt.plot(x1,model.fittedvalues,'r--',label='ols')
plt.plot(x1,interval_u,'r--')
plt.plot(x1,interval_l,'r--')
plt.legend(loc='best')
plt.show()

 

Attention:

非线性回归 

#1.可线性化的非线性回归
formula='sales~registration+np.square(registration)+cube(registration)'
eb_model=ols(formula,data=eb).fit()
#2.分位数回归
from statsmodels.formula.api import quantreg
formula='Current_Salary~Begin_Salary+Education+Experience'
model2=quantreg(formula,data=salary).fit(q=0.1)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章