Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data(iris)
- dim(iris)[[1]]
- ##split the data based on its class
- NewData <- split(iris, iris$Species)
- ## divide the data based on their class
- NewDatSetosa <- NewData$setosa[,1:4]
- NewDatVersicolor <- NewData$versicolor[,1:4]
- NewDatVirginica <- NewData$virginica[,1:4]
- ##divide the data into train and test datasets
- set.seed(1234)
- datadivision <- sample(2, nrow(iris), replace=TRUE, prob=c(0.67, 0.33))
- iris.training <- iris[datadivision==1, 1:4]
- iris.test <- iris[datadivision==2, 1:4]
- ##Compute the posterior for each class
- posterior <- function(data,prior,newDat){
- post <- list()
- ##compute the density for each point in the training data set
- den <- lapply(1:4, function(i) dnorm(data[[i]], mean(newDat[[i]]), sd(newDat[[i]])))
- ## compute the posterior for each point. den[[1]] is the density of the
- Sepal.Length. den[2] is the density of Sepal.Width. den[3] and den[4] are the density for the resining variables.
- post <- prior*den[[1]]*den[[2]]*den[[3]]*den[[4]]
- return(post)
- }
- post.Setosa <- posterior(iris.training, prior=0.3, NewDatSetosa)
- post.Versicolor <- posterior(iris.training, prior=0.3, NewDatVersicolor)
- post.Virginica <- posterior(iris.training, prior=0.3, NewDatVirginica)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement