nb_model: Multinomial Naive Bayes for Text Classification

View source: R/nb.R

nb_modelR Documentation

Multinomial Naive Bayes for Text Classification

Description

Multinomial Naive Bayes for Text Classification

Usage

nb_model(
  train_vectorized,
  Y,
  test_vectorized,
  parallel = FALSE,
  tune = FALSE,
  weights = NULL
)

Arguments

train_vectorized

The training feature matrix (e.g., a 'dfm' from quanteda). This should be a sparse matrix.

Y

The response variable for the training set. Should be a factor for classification.

test_vectorized

The test feature matrix, which must have the same features as 'train_vectorized'

parallel

Logical

tune

Logical. If TRUE, tests different Laplace smoothing values.

weights

A numeric vector of observation weights. Default is NULL

Value

A list containing four elements:

pred

A vector of class predictions for the test set.

probs

A matrix of predicted probabilities.

model

The final, trained 'naivebayes' model object.

best_lambda

Placeholder (NULL) for pipeline consistency.

Examples

# 1. Create dummy numeric matrices with BOTH row and column names
train_matrix <- matrix(
  as.numeric(sample(0:5, 100, replace = TRUE)),
  nrow = 10, ncol = 10,
  dimnames = list(paste0("doc", 1:10), paste0("word", 1:10))
)

test_matrix <- matrix(
  as.numeric(sample(0:5, 50, replace = TRUE)),
  nrow = 5, ncol = 10,
  dimnames = list(paste0("doc", 1:5), paste0("word", 1:10))
)

# 2. Create dummy target variable
y_train <- factor(sample(c("P", "N"), 10, replace = TRUE))

# 3. Run model
model_results <- nb_model(train_matrix, y_train, test_matrix)
print(model_results$pred)

quickSentiment documentation built on Aug. 29, 2026, 1:07 a.m.