14.6 Implementation
To implement naive Bayes classification in R
, we’ll use the naiveBayes()
function in the e1071
package (Meyer et al. 2021)
14.6.1 Models
# two models
<- naiveBayes(species ~ bill_length_mm, data = penguins)
naive_model_1 <- naiveBayes(species ~ bill_length_mm + flipper_length_mm,
naive_model_2 data = penguins)
# our penguin to classify
<- data.frame(bill_length_mm = 50, flipper_length_mm = 195) our_penguin
14.6.2 Predictions
predict(naive_model_1, newdata = our_penguin, type = "raw") |>
round(6)
## Adelie Chinstrap Gentoo
## [1,] 0.000169 0.397831 0.602
predict(naive_model_1, newdata = our_penguin)
## [1] Gentoo
## Levels: Adelie Chinstrap Gentoo
predict(naive_model_2, newdata = our_penguin, type = "raw") |>
round(6)
## Adelie Chinstrap Gentoo
## [1,] 0.000345 0.994868 0.004787
predict(naive_model_2, newdata = our_penguin)
## [1] Chinstrap
## Levels: Adelie Chinstrap Gentoo