# library(naivebayes)
### Simulate the data:
cols <- 10 ; rows <- 100
M <- matrix(sample(0:5, rows * cols, TRUE, prob = c(0.95, rep(0.01, 5))), nrow = rows, ncol = cols)
y <- factor(sample(paste0("class", LETTERS[1:2]), rows, TRUE, prob = c(0.3,0.7)))
colnames(M) <- paste0("V", seq_len(ncol(M)))
laplace <- 1
### Train the Multinomial Naive Bayes
mnb <- multinomial_naive_bayes(x = M, y = y, laplace = laplace)
summary(mnb)
# Classification
head(predict(mnb, newdata = M, type = "class")) # head(mnb %class% M)
# Posterior probabilities
head(predict(mnb, newdata = M, type = "prob")) # head(mnb %prob% M)
# Parameter estimates
coef(mnb)
### Sparse data: train the Multinomial Naive Bayes
library(Matrix)
M_sparse <- Matrix(M, sparse = TRUE)
class(M_sparse) # dgCMatrix
# Fit the model with sparse data
mnb_sparse <- multinomial_naive_bayes(M_sparse, y, laplace = laplace)
# Classification
head(predict(mnb_sparse, newdata = M_sparse, type = "class"))
# Posterior probabilities
head(predict(mnb_sparse, newdata = M_sparse, type = "prob"))
# Parameter estimates
coef(mnb_sparse)
Run the code above in your browser using DataLab