##Uncomment if use this package for the first time
##install.packages("tree");
library(tree);
class.ind<-function (cl)
{
n <- length(cl);
cl <- as.factor(cl);
x <- matrix(0, n, length(levels(cl)));
x[(1L:n) + n * (unclass(cl) - 1L)] <- 1;
dimnames(x) <- list(names(cl), levels(cl));
x
}
data(iris);
n<-nrow(iris);
idx<-sample(1:n, floor(n/2), replace=FALSE);
iris_train<-iris[idx,]; iris_test<-iris[-idx,];
labels<-class.ind(iris$Species);
myiris<-tree(Species ~ ., data=iris_train);
plot(myiris); text(myiris);
test.cl <- function(true, pred) {
true <- max.col(true)
cres <- max.col(pred)
table(true, cres)
}
conf<-test.cl(labels[-idx,], predict(myiris, iris_test));
acc<-sum(diag(conf))/sum(conf);
cat("The accuracy on the test set is", acc,"\n");