TrainB<-read.table("TrainB.dat") names(TrainB)<-c("x1","x2","y") y<-class.ind(TrainB$y) TrainB.c <- data.frame(TrainB,y) g.a <- lm( a ~ x1 + x2, data = TrainB.c ) g.b <- lm( b ~ x1 + x2, data = TrainB.c ) g.c <- lm( c ~ x1 + x2, data = TrainB.c ) a.a <- predict(g.a, TrainB ) a.b <- predict(g.b, TrainB ) a.c <- predict(g.c, TrainB ) yhat<-rep('d',150) for( i in 1:150 ) { if( (a.a[i] > a.b[i]) && (a.a[i] > a.c[i])) yhat[i] <- "a" } for( i in 1:150 ) { if( (a.b[i] > a.a[i]) && (a.b[i] > a.c[i])) yhat[i] <- "b" } for( i in 1:150 ) { if( (a.c[i] > a.a[i]) && (a.c[i] > a.b[i])) yhat[i] <- "c" } yhat.c <- class.ind(yhat) err=abs(y-yhat.c) sum(err[,1],err[,2],err[,3]) err.t<-sum(err[,1],err[,2],err[,3])/2 par(mfcol=c(1,2)) xp <- seq(min(TrainB$x1), max(TrainB$x1), length = 100); np <- length(xp) yp <- seq(min(TrainB$x2), max(TrainB$x2), length = 100); pt <- expand.grid(x1 = xp, x2 = yp) Z.a <- predict(g.a, pt) Z.b <- predict(g.b, pt) Z.c <- predict(g.c, pt) plot(TrainB$x1,TrainB$x2, col=codes(TrainB$y)) title("Linear Model for TrainB") zp <- Z.a - pmax(Z.b, Z.c) contour(xp, yp, matrix(zp, np), add = T, levels = 0, labex = 0) zp <- Z.c - pmax(Z.a, Z.b) contour(xp, yp, matrix(zp, np), add = T, levels = 0, labex = 0) mtext(paste("Plug-In Error=",format(100*err.t/150,digits=3),"%")) TestB <- read.table("TestB.dat") names(TestB)<-c("x1","x2") N <- length(TestB[,1]) aT.a <- predict(g.a, TestB ) aT.b <- predict(g.b, TestB ) aT.c <- predict(g.c, TestB ) yThat<-rep('d', N) for( i in 1:N) { if( (aT.a[i] > aT.b[i]) && (aT.a[i] > aT.c[i])) yThat[i] <- "a" } for( i in 1:N) { if( (aT.b[i] > aT.a[i]) && (aT.b[i] > aT.c[i])) yThat[i] <- "b" } for( i in 1:N) { if( (aT.c[i] > aT.a[i]) && (aT.c[i] > aT.b[i])) yThat[i] <- "c" } xp <- seq(min(TestB$x1), max(TestB$x1), length = 100); np <- length(xp) yp <- seq(min(TestB$x2), max(TestB$x2), length = 100); pt <- expand.grid(x1 = xp, x2 = yp) Z.a <- predict(g.a, pt) Z.b <- predict(g.b, pt) Z.c <- predict(g.c, pt) plot(TestB$x1,TestB$x2, col=codes(as.factor(yThat))) title("Linear Model for TestB") zp <- Z.a - pmax(Z.b, Z.c) contour(xp, yp, matrix(zp, np), add = T, levels = 0, labex = 0) zp <- Z.c - pmax(Z.a, Z.b) contour(xp, yp, matrix(zp, np), add = T, levels = 0, labex = 0) Result<-data.frame(TestB,yThat) write.table(Result,"TestB-C-LM.dat", quote=F, col.names=F, row.names=F)