rm(list=ls()) read.table("datenb3.txt",header=TRUE)->tab t<-tab[,1] y<-tab[,2] plot(t,y,pch=16,cex=0.5) curve(10*(5*x^4-7*x^3+2*x^2)+4*x,0,1,add=TRUE,col=2) lines(ksmooth(t,y,kernel="normal",bandwidth=0.2),col=3,lwd=2) lines(ksmooth(t,y,kernel="normal",bandwidth=0.05),col=4,lwd=2) lines(ksmooth(t,y,kernel="normal",bandwidth=0.5),col=5,lwd=2) legend("topleft",legend=c("echte Kurve", "bw=0.2","bw=0.05","bw=0.5"),col=2:5,lwd=c(1,rep(2,3))) library(KernSmooth) plot(t,y,pch=16,cex=0.5) curve(10*(5*x^4-7*x^3+2*x^2)+4*x,0,1,add=TRUE,col=2) lines(locpoly(t,y,bandwidth=0.05),lwd=2,col=3) lines(locpoly(t,y,bandwidth=0.1),lwd=2,col=4) lines(locpoly(t,y,bandwidth=0.2),lwd=2,col=5) lines(locpoly(t,y,bandwidth=0.5),lwd=2,col=6) legend("topleft",legend=c("echte Kurve", "bw=0.05","bw=0.1","bw=0.2",bw=0.5),col=2:6,lwd=c(1,rep(2,4))) ### Aufg 3 n<-length(y) #alles zusammen, mit wenige Stützstellen cv<-c() ha<-seq(0.02,0.2,by=0.02) par(mfrow=c(1,3)) cvall<-matrix(NA,length(ha),3) for (deg in 1:3){ for (k in 1:length(ha)){ hatm<-rep(NA,n) for (i in 1:n){ datenm<-cbind(t[-i],y[-i]) fitm<-locpoly(datenm[,1],datenm[,2],bandwidth=ha[k],gridsize=101,range.x=c(0,1),degree=deg) #lines(fitm) hatm[i]<-fitm$y[i] } cv[k]<-1/n*sum((y-hatm)^2) } cvall[,deg]<-cv plot(ha,cvall[,deg]) lines(ha,cvall[,deg],col=2) } # Genauer: # für deg=1 ha<-seq(0.045,0.06,by=0.001) for (k in 1:length(ha)){ hatm<-rep(NA,n) for (i in 1:n){ datenm<-cbind(t[-i],y[-i]) fitm<-locpoly(datenm[,1],datenm[,2],bandwidth=ha[k],gridsize=101,range.x=c(0,1),degree=1) hatm[i]<-fitm$y[i] } cv[k]<-1/n*sum((y-hatm)^2) } h1<-ha[which.min(cv)] h1 #für deg=2 ha<-seq(0.09,0.11,by=0.001) for (k in 1:length(ha)){ hatm<-rep(NA,n) for (i in 1:n){ datenm<-cbind(t[-i],y[-i]) fitm<-locpoly(datenm[,1],datenm[,2],bandwidth=ha[k],gridsize=101,range.x=c(0,1),degree=2) #lines(fitm) hatm[i]<-fitm$y[i] } cv[k]<-1/n*sum((y-hatm)^2) } h2<-ha[which.min(cv)] h2 # für deg=3 ha<-seq(0.1,0.13,by=0.001) for (k in 1:length(ha)){ hatm<-rep(NA,n) for (i in 1:n){ datenm<-cbind(t[-i],y[-i]) fitm<-locpoly(datenm[,1],datenm[,2],bandwidth=ha[k],gridsize=101,range.x=c(0,1),degree=3) #lines(fitm) hatm[i]<-fitm$y[i] } cv[k]<-1/n*sum((y-hatm)^2) } h3<-ha[which.min(cv)] h3 plot(t,y,pch=16,cex=0.5) curve(10*(5*x^4-7*x^3+2*x^2)+4*x,0,1,add=TRUE,col=2) lines(locpoly(t,y,bandwidth=h1),lwd=2,col=3) lines(locpoly(t,y,bandwidth=h2,degree=2),lwd=2,col=4) lines(locpoly(t,y,bandwidth=h3,degree=3),lwd=2,col=5) legend("topleft",legend=c("echte Kurve","1. Grad", "2. Grad", "3. Grad"),col=2:5,lwd=c(1,rep(2,3)))