library(naivebayes)
### Simulate the data:
cols <- 10 ; rows <- 100
M <- matrix(rpois(rows * cols, lambda = 3), 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 <- 0.5
### Train the Poisson Naive Bayes
pnb <- poisson_naive_bayes(x = M, y = y, laplace = laplace)
summary(pnb)
# Classification
head(predict(pnb, newdata = M, type = "class")) # head(pnb %class% M)
# Posterior probabilities
head(predict(pnb, newdata = M, type = "prob")) # head(pnb %prob% M)
# Parameter estimates
coef(pnb)
### Sparse data: train the Poisson Naive Bayes
library(Matrix)
M_sparse <- Matrix(M, sparse = TRUE)
class(M_sparse) # dgCMatrix
# Fit the model with sparse data
pnb_sparse <- poisson_naive_bayes(M_sparse, y, laplace = laplace)
# Classification
head(predict(pnb_sparse, newdata = M_sparse, type = "class"))
# Posterior probabilities
head(predict(pnb_sparse, newdata = M_sparse, type = "prob"))
# Parameter estimates
coef(pnb_sparse)
### Equivalent calculation with general naive_bayes function.
### (no sparse data support by naive_bayes)
nb <- naive_bayes(M, y, laplace = laplace, usepoisson = TRUE)
summary(nb)
head(predict(nb, type = "prob"))
# Obtain probability tables
tables(nb, which = "V1")
tables(pnb, which = "V1")
# Visualise class conditional Poisson distributions
plot(nb, "V1", prob = "conditional")
plot(pnb, which = "V1", prob = "conditional")
# Check the equivalence of the class conditional distributions
all(get_cond_dist(nb) == get_cond_dist(pnb))
Run the code above in your browser using DataLab