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)

 

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