Advertisement
Guest User

Untitled

a guest
Aug 21st, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. # Packages
  2. library(klaR)
  3. library(MASS)
  4.  
  5. # Data
  6. d <- structure(list(y = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L), .Label = c("0", "1"), class = "factor"), x1 = c(2, 2.8, 1.5, 2.1, 5.5, 8, 6.9, 8.5, 2.5, 7.7), x2 = c(1.5, 1.2, 1, 1, 4, 4.8, 4.5, 5.5, 2, 3.5)), .Names = c("y", "x1", "x2"), row.names = c(NA, -10L), class = "data.frame")
  7.  
  8. # Naive Bayes Model
  9. mN <- NaiveBayes(y ~ x1+x2, data = d)
  10.  
  11. # Data
  12.  
  13. # Class 1
  14. m1 <- mean(d[which(d$y==1),]$x1)
  15. m2 <- mean(d[which(d$y==1),]$x2)
  16. mu1_2 <- c(m1,m2) # Mean
  17. sd1 <- sd(d[which(d$y==1),]$x1)
  18. sd2 <- sd(d[which(d$y==1),]$x2)
  19. Sigma1_2 <- matrix(c(sd1, 0, 0, sd2), 2) # Covariance matrix
  20. bivn1_2 <- mvrnorm(5000, mu = mu1_2, Sigma = Sigma1_2 ) # from Mass package: Simulate bivariate normal PDF
  21. bivn1_2.kde <- kde2d(bivn1_2[,1], bivn1_2[,2], n = 50) # from MASS package: Calculate kernel density estimate
  22.  
  23.  
  24. # Class 0
  25. m3 <- mean(d[which(d$y==0),]$x1)
  26. m4 <- mean(d[which(d$y==0),]$x2)
  27. mu3_4 <- c(m3,m4) # Mean
  28. sd3 <- sd(d[which(d$y==0),]$x1)
  29. sd4 <- sd(d[which(d$y==0),]$x2)
  30. Sigma3_4 <- matrix(c(sd3, 0, 0, sd4), 2) # Covariance matrix
  31. bivn3_4 <- mvrnorm(5000, mu = mu3_4, Sigma = Sigma3_4 ) # from Mass package: Simulate bivariate normal PDF
  32. bivn3_4.kde <- kde2d(bivn3_4[,1], bivn3_4[,2], n = 50) # from MASS package: Calculate kernel density estimate
  33.  
  34.  
  35. # Plot
  36. plot(x= d$x1, y=d$x2, xlim=c(-1,10), ylim=c(-1,10), col=d$y, pch=19, cex=2, ylab="x2", xlab="x1")
  37. contour(bivn1_2.kde, add = TRUE, col="darkgrey") # from base graphics package
  38. contour(bivn3_4.kde, add = TRUE, col="darkgrey") # from base graphics package
  39. text(labels = "Class 1",x = 8, y=7, col="grey")
  40. text(labels = "Class 0",x = 0, y=4, col="grey")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement