Skip to content

Instantly share code, notes, and snippets.

@nqbao
Created June 25, 2016 17:03
Show Gist options
  • Save nqbao/de2e48c832a06cc3af60810dccbb7b06 to your computer and use it in GitHub Desktop.
Save nqbao/de2e48c832a06cc3af60810dccbb7b06 to your computer and use it in GitHub Desktop.
# An example of using decision tree to classify iris data
library("party")
splitdf <- function(dataframe, ratio=0.8, seed=NULL) {
if (!is.null(seed)) set.seed(seed)
index <- 1:nrow(dataframe)
trainindex = sample(1:nrow(dataframe), size=ratio*nrow(dataframe))
trainset <- dataframe[trainindex, ]
testset <- dataframe[-trainindex, ]
list(train=trainset,test=testset)
}
split = splitdf(iris)
tree <- ctree(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data=split$train)
plot(tree)
predicted = predict(tree, split$test)
calculate_accuracy = function(predicted, actual) {
d = table(predicted, actual)
sum(diag(d))/sum(d)
}
calculate_accuracy(predicted, split$test$Species)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment