非线性回归模型、多项式回归、局部回归的r语言代码

#非线性回归模型
setwd("I:/研一课程/2.2回归分析/R/data")#设定当前的工作目录,重要!
a<-read.table("2.txt",header=T)
a.nls<-nls(y~k*a^(b^t),data=a,start=list(k=149,a=0.01,b=0.8))
a.sum<-summary(a.nls)
a.sum  #(1)采用龚珀兹模型形式,建立非线性模型
SST<-sum((a$y-mean(a$y))**2) #计算Rsquare
Rsquare<-1-a.sum$sigma^2*df.residual(a.nls)/SST
Rsquare


#多项式回归
setwd("I:/研一课程/2.2回归分析/R/data")#设定当前的工作目录,重要!
a<-read.table("2.txt",header=T)
income.plm<-lm(y~t+I(t^2),data=a)
summary(income.plm)


#-----------------------------------------------------------#局部回归
#核回归光滑模型1
setwd("I:/研一课程/2.2回归分析/R/data")#设定当前的工作目录,重要!
d<-read.table("2.txt",header=T)
par(mfrow=c(2,1));X=d[,1];Y=d[,2];
bw=list(" (a) normal", " (b) box")
plot(X,Y,main=bw[[1]]);lines(ksmooth(X,Y, "normal", bandwidth=5))
plot(X,Y,main=bw[[2]]);lines(ksmooth(X,Y, "box", bandwidth=5))


#核回归光滑模型2
par(mfrow=c(2,2))
bw=list(" (a) h=1", " (b) h=2", " (c) h=3", " (d) h=5")
plot(X,Y,main=bw[[1]]);lines(ksmooth(X,Y, "normal", bandwidth=1))
plot(X,Y,main=bw[[2]]);lines(ksmooth(X,Y, "normal", bandwidth=2))
plot(X,Y,main=bw[[3]]);lines(ksmooth(X,Y, "normal", bandwidth=3))
plot(X,Y,main=bw[[4]]);lines(ksmooth(X,Y, "normal", bandwidth=5))


#求最优的带宽h
source("gcvbandNW.R")
gcvbandNW(X,Y)


#k近邻回归1
#install.packages("kknn")
library(kknn)
kknnest1<-kknn(formula=Y~X,d,d,k=5,kernel="rectangular")
kknnest2<-kknn(formula=Y~X,d,d,k=11,kernel="rectangular")
#kknnest<-kknn(formula=Y~X,d,d,k=11,kernel="gaussian")
par(mfrow=c(2,1));
bw=list(" (a) k=5", " (b) k=11")
plot(X,Y,main=bw[[1]]);lines(X,kknnest1$fitted.values)
plot(X,Y,main=bw[[2]]);lines(X,kknnest2$fitted.values)
source("gcvbandKN.R")
gcvbandKN(X,Y)


#k近邻回归2
kknnest1<-kknn(formula=Y~X,d,d,k=11,kernel="rectangular")
kknnest2<-kknn(formula=Y~X,d,d,k=11,kernel="gaussian")
par(mfrow=c(2,1));
bw=list(" (a) unweighted,k=11", " (b) Gaussian,k=11")
plot(X,Y,main=bw[[1]]);lines(X,kknnest1$fitted.values)
plot(X,Y,main=bw[[2]]);lines(X,kknnest2$fitted.values)


#k近邻回归3
kknnest1<-kknn(formula=Y~X,d,d,k=11,kernel="rectangular")
kknnest2<-kknn(formula=Y~X,d,d,k=11,kernel="gaussian")
par(mfrow=c(2,2));
bw=list(" (a) knn: unweighted,k=11", " (b) knn: Gaussian,k=11", "
 (c) NW:box,h=2.5", " (d) NW:normal,h=2.5")
plot(X,Y,main=bw[[1]]);lines(X,kknnest1$fitted.values)
plot(X,Y,main=bw[[2]]);lines(X,kknnest2$fitted.values)
plot(X,Y,main=bw[[3]]);lines(ksmooth(X,Y, "box", bandwidth=2.5))
plot(X,Y,main=bw[[4]]);lines(ksmooth(X,Y, "normal", bandwidth=2.5))


#局部多项式回归1
#install.packages("KernSmooth")
library(KernSmooth); 
par(mfrow=c(2,2));
bw=list(" (a) h=0.25", " (b) h=0.50", " (c) h=0.75", " (d) h=1")
plot(X,Y, main=bw[[1]])
fit1 <- locpoly(X, Y, bandwidth =0.25)
lines(fit1)
plot(X,Y, main=bw[[2]])
fit2 <- locpoly(X, Y, bandwidth =0.5)
lines(fit2)
plot(X,Y, main=bw[[3]])
fit3 <- locpoly(X, Y, bandwidth =0.75)
lines(fit3)
plot(X,Y, main=bw[[4]])
fit4 <- locpoly(X, Y, bandwidth =1)
lines(fit4)



你可能感兴趣的:(非线性回归模型,多项式回归,局部回归,最)