2025年3月22日 星期六

透過線性模型瞭解交互作用項與平方項對依變項擬合過程的重要性

 


數據來源採用SAS內建資料集,如下:



透過call streaminit()快速且有效率地把資料放大(每一位同學資料變出10筆觀察值)。

data class2; 
set sashelp.class; 
call streaminit(20171105);   *種子序, 迴圈內隨機跑出數據。若給予一個固定種子序值,每次跑出來的結果會相同;
do enhance=1 to 10; 
height = height+rand("Normal")*2; 
weight = weight+rand("Normal")*4; 
output; 
end; 
run; 

結果如下,本案只用Sex(自變數), Height(自變數), Weight(依變數),用前兩者預測後者。



Proc sgplot的 pbspline statement可針對上述資料分布快速擬合出曲線,如下:

ods graphics on; 
title PBSPLINE Fit of Weight as a Function of Height and Sex; 
proc sgplot data=class; 
pbspline x=height y=weight/group=sex clm alpha=0.05  nknots=5 nolegclm; 
*nknots的值愈大,擬合愈高(過高有過度擬合問題), clm即要求SAS產生95%信賴區間色帶;
xaxis grid; 
yaxis grid; 
run; 
ods graphics close; title;


Proc sgplot的 reg statement可針對上述資料分布快速擬合出直線,如下:

ods graphics on; 
title  Regression Fit of Weight as a Function of Height and Sex; 
proc sgplot data=class2; 
reg x=height y=weight /group=sex clm alpha=0.05; 
xaxis grid; 
yaxis grid; 
run; 
ods graphics off; title;


透過Proc genmod (可跑logistic, binomial, poisson或其它模型)執行簡易迴歸分析,如下:

proc genmod data=class2; 
class sex;
model weight=height | sex /dist=NOR wald type3; 
*  | 意即自變項除了height, sex,也包含交互作用項  height*sex;
*原始寫法即 height sex height*sex;
run; 


上表: 
1.說明身高對體重有顯著性影響(見上黃)
2.沒有證據表明性別對線性模型中的體重有影響(見中黃)
3.說明性別*高度這個交互作用項在線性模型中不重要(見下黃)

前面的統計圖說明身高和體重關係不是線性,且會被性別影響,所以來小改指令。
既然不是線性,平方項就大膽放入模型中評估。
數據中男性較多,故以男性當ref並給予0代碼。
另外,因為交互項名字太長,怕在統計表中名稱被斷頭,故強制給予38的寬度。

proc genmod data=class2 namelen=38; 
class sex/order=freq param=ref ref=first; 
model weight=height | sex   height*height  height*height*sex   /dist=nor wald type3; 
run; 


結果顯示截距項和所有自變項均呈顯著性(上表)。

所以模型已確定,接下來再下一次語法並把統計結果匯出成dataset準備畫圖。

proc genmod data=class2 namelen=38; 
class sex/order=freq param=ref ref=first missing; 
model weight=height | sex    height*height     height*height*sex   /dist=nor wald type3; 
output out=pred p=p  l=Lower u=Upper; 
run; 

pred的dataset如下:
p即預測值,後兩者依序為下限值和上限值,此檔將用於製圖。

proc sort data=pred tagsort noequals force; 
by sex height weight; 
run; 

ods graphics on; 
proc sgplot data=pred; 
band x=height lower=lower upper=upper / group=sex; 
scatter y=weight x=height / group=sex; 
series y=p x=height /  lineattrs=GraphPrediction group=sex; 
xaxis grid; 
yaxis grid; 
keylegend; 
run; 
ods graphics off; title;

模型擬合後統計圖(納入交互作用項與平方項)如下:


再來看一眼利用pbspline statement偷吃步法繪製的統計圖,如下:


由於pbspline statement在Proc sgplot下,能控制和修正參數的程度有限,故利用pbspline statement畫這種多項次線性圖,只能視為資料態樣初探。

還記得最一開始,統計結果顯示身高有顯著性影響,但性別與身高*性別交互作用項沒有顯著性影響(平方項未納入)。此結果模型若拿來預測並繪圖,就產生如下結果:


可發現圖呈現的資訊與你大腦對資料點分布的預想迴歸線有極大落差。再說白些,這張圖有跑比沒跑還差。

如果本文章提供的資訊對你有幫助,可以考慮請我喝飲料(金額隨喜),謝謝。
台新銀行帳戶

沒有留言: