Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. data(iris)
  2. dim(iris)[[1]]
  3. ##split the data based on its class
  4. NewData <- split(iris, iris$Species)
  5. ## divide the data based on their class
  6. NewDatSetosa <- NewData$setosa[,1:4]
  7. NewDatVersicolor <- NewData$versicolor[,1:4]
  8. NewDatVirginica <- NewData$virginica[,1:4]
  9.  
  10. ##divide the data into train and test datasets
  11. set.seed(1234)
  12. datadivision <- sample(2, nrow(iris), replace=TRUE, prob=c(0.67, 0.33))
  13. iris.training <- iris[datadivision==1, 1:4]
  14. iris.test <- iris[datadivision==2, 1:4]
  15. ##Compute the posterior for each class
  16.  
  17. posterior <- function(data,prior,newDat){
  18. post <- list()
  19. ##compute the density for each point in the training data set
  20. den <- lapply(1:4, function(i) dnorm(data[[i]], mean(newDat[[i]]), sd(newDat[[i]])))
  21. ## compute the posterior for each point. den[[1]] is the density of the
  22. Sepal.Length. den[2] is the density of Sepal.Width. den[3] and den[4] are the density for the resining variables.
  23. post <- prior*den[[1]]*den[[2]]*den[[3]]*den[[4]]
  24. return(post)
  25. }
  26. post.Setosa <- posterior(iris.training, prior=0.3, NewDatSetosa)
  27. post.Versicolor <- posterior(iris.training, prior=0.3, NewDatVersicolor)
  28. post.Virginica <- posterior(iris.training, prior=0.3, NewDatVirginica)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement