複雜統計方法R語言——簡單迴歸

簡單迴歸

數據來源:http://www.statsci.org/data/general/cofreewy.html

 

1.讀入數據

setwd("D:/數學建模/寒假美賽集訓/R統計")
w=read.table("COfreewy.txt",header=T,encoding = "utf-8")

 

2.線性迴歸

a=lm(CO~.,w)
#a=lm(CO~Traffic+Wind,w)#線性迴歸
#print(w)
summary(a)

 第一列爲迴歸係數,第二列爲標準差,一般都<0.05較好,第四列爲p值。原假設爲:係數爲0。p<0.05,則拒絕原假設。若p>0.05,可以考慮去除該變量再做一次迴歸,以使每一個p值都<0.05。

 

3.AIC逐步迴歸

b=step(a,direction = "backward")#逐步迴歸
summary(b)

通過使用逐步迴歸,我們選擇了變量,捨棄了Hour變量,每一個p值都<0.05。

 

4.殘差檢驗

shapiro.test(b$res)#做殘差的正態性檢驗

 $y-\hat{y}$爲殘差,應符合正態分佈,均值爲0。如果均值不爲0,則存在系統誤差。

 

5.畫出qq圖

qqnorm(b$res);qqline(b$res)#查看回歸殘差的qq圖

qq圖有兩個作用:1、檢驗一組數據是否服從某一分佈。2、檢驗兩個分佈是否服從同一分佈。qq圖全稱是quantile-quantile plot,從名稱中可以瞭解到是和分位數相關的圖。qq圖沒有過原點,說明仍存在一定系統誤差。

 

 

6.各變量散點圖

plot(w)
#pairs(w)

 

7.傅里葉技術變換

cor(cbind(CO,Traffic,Tsq=Traffic^2,Tcub=Traffic^3,
          Hour,Hsq=Hour^2,Hcub=Hour^3,Wind,Wsq=Wind^2,Wcub=Wind^3))
a=lm(CO~Traffic+Wind+I(Wind^2)+I(Wind^3)+sin((2*pi/24)*Hour)+
  cos((2*pi/24)*Hour)+sin((4*pi/24)*Hour)+cos((4*pi/24)*Hour))
b=step(a) #逐步迴歸,按照aIC選擇變量
summary(b);anova(b);shapiro.test(b$res)

b1=lm(CO~Traffic+Wind+I(Wind^2)+
        cos((2*pi/24)*Hour)+cos((4*pi/24)*Hour))
summary(b1)
anova(b1)#方差分析表
shapiro.test(b1$res)#對殘差的正態性檢驗
qqnorm(b$res);qqline(b$res)#查看回歸殘差的qq圖

 

 

 

 

 

 所有代碼:

setwd("D:/數學建模/寒假美賽集訓/R統計")
w=read.table("COfreewy.txt",header=T,encoding = "utf-8")
attach(w)#把數據變成全局變量
print(CO)
head(w)#查看前6條數據
a=lm(CO~.,w)
#a=lm(CO~Traffic+Wind,w)#線性迴歸
#print(w)
summary(a)

b=step(a,direction = "backward")#逐步迴歸
summary(b)

shapiro.test(b$res)#做殘差的正態性檢驗

qqnorm(b$res);qqline(b$res)#查看回歸殘差的qq圖

par(mfrow=c(2,3))#同時顯示6張圖
plot(Traffic,Wind)
plot(CO,Wind)
plot(Traffic,CO)
plot(Hour,Wind)
plot(CO,Hour)
plot(Hour,Traffic)
plot(w)
#pairs(w)

cor(cbind(CO,Traffic,Tsq=Traffic^2,Tcub=Traffic^3,
          Hour,Hsq=Hour^2,Hcub=Hour^3,Wind,Wsq=Wind^2,Wcub=Wind^3))
a=lm(CO~Traffic+Wind+I(Wind^2)+I(Wind^3)+sin((2*pi/24)*Hour)+
  cos((2*pi/24)*Hour)+sin((4*pi/24)*Hour)+cos((4*pi/24)*Hour))
b=step(a) #逐步迴歸,按照aIC選擇變量
summary(b);anova(b);shapiro.test(b$res)

b1=lm(CO~Traffic+Wind+I(Wind^2)+
        cos((2*pi/24)*Hour)+cos((4*pi/24)*Hour))
summary(b1)
anova(b1)#方差分析表
shapiro.test(b1$res)#對殘差的正態性檢驗
par(mfrow=c(1,1))
qqnorm(b$res);qqline(b$res)#查看回歸殘差的qq圖

  

  

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