| Title: | Threshold-Based and Iterative Threshold-Based Naive Bayes Classifier |
|---|---|
| Description: | Implements the Threshold-Based Naive Bayes (Tb-NB) classifier and its iterative refinement (iTb-NB) for binary sentiment / text classification problems. The classifier computes a continuous log-likelihood ratio score per document and uses a data-driven decision threshold estimated via K-fold cross-validation on a user-selected criterion (accuracy, F1 score, Matthews correlation coefficient, balanced error, etc.). An optional iterative refinement procedure locally re-estimates the threshold in regions of class overlap using either Gaussian kernel density estimation or a Central Limit Theorem bootstrap approximation. The package exposes an idiomatic R formula + data.frame interface together with a 'quanteda'-based text preprocessing pipeline, supports user-supplied document-feature matrices, and includes an optional word-embedding extension that augments the Bag-of-Words with K nearest semantic neighbours of each token. The package additionally implements the p-value extension proposed by Romano (2025) for both document- and feature-level interpretability via tbnb_pvalues(). Methods are described in Romano, Contu, Mola, Conversano (2024) <doi:10.1007/s11634-023-00536-8>, Romano, Zammarchi, Conversano (2024) <doi:10.1007/s10260-023-00721-1>, and Romano (2025) <doi:10.1007/978-3-031-96736-8_41>. |
| Authors: | Maurizio Romano [aut, cre] |
| Maintainer: | Maurizio Romano <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 0.1.0 |
| Built: | 2026-07-21 12:24:07 UTC |
| Source: | https://github.com/cran/tbnb |
itbnb() fits the Threshold-Based Naive Bayes classifier proposed by
Romano et al. (2024) and, optionally, its iterative refinement
(iTb-NB). The method is designed for binary classification of text
documents but accepts any binary Bag-of-Words–style feature matrix.
itbnb(...) ## S3 method for class 'formula' itbnb( formula, data, subset, na.action, preprocess = tbnb_preprocess(), embedding = NULL, alpha = 1, fit_prior = TRUE, class_prior = NULL, optimize_threshold = TRUE, criterion = "balanced_error", tau_grid = "observed", n_tau = 50L, K = 5L, random_state = 42L, iterative = FALSE, iter_mode = c("kde", "clt"), p_iter = 0.2, s_iter = 20L, clt_n_boot = 500L, clt_sample_size = 30L, language_col = NULL, ... ) ## Default S3 method: itbnb( x, y, preprocess = NULL, embedding = NULL, alpha = 1, fit_prior = TRUE, class_prior = NULL, optimize_threshold = TRUE, criterion = "balanced_error", tau_grid = "observed", n_tau = 50L, K = 5L, random_state = 42L, iterative = FALSE, iter_mode = c("kde", "clt"), p_iter = 0.2, s_iter = 20L, clt_n_boot = 500L, clt_sample_size = 30L, doc_languages = NULL, ... )itbnb(...) ## S3 method for class 'formula' itbnb( formula, data, subset, na.action, preprocess = tbnb_preprocess(), embedding = NULL, alpha = 1, fit_prior = TRUE, class_prior = NULL, optimize_threshold = TRUE, criterion = "balanced_error", tau_grid = "observed", n_tau = 50L, K = 5L, random_state = 42L, iterative = FALSE, iter_mode = c("kde", "clt"), p_iter = 0.2, s_iter = 20L, clt_n_boot = 500L, clt_sample_size = 30L, language_col = NULL, ... ) ## Default S3 method: itbnb( x, y, preprocess = NULL, embedding = NULL, alpha = 1, fit_prior = TRUE, class_prior = NULL, optimize_threshold = TRUE, criterion = "balanced_error", tau_grid = "observed", n_tau = 50L, K = 5L, random_state = 42L, iterative = FALSE, iter_mode = c("kde", "clt"), p_iter = 0.2, s_iter = 20L, clt_n_boot = 500L, clt_sample_size = 30L, doc_languages = NULL, ... )
... |
Currently unused. |
formula |
A formula of the form |
data |
A |
subset |
Optional logical / integer vector for row subsetting (only used by the formula interface). |
na.action |
What to do with NA values (formula interface). |
preprocess |
A configuration produced by |
embedding |
A configuration produced by |
alpha |
Laplace smoothing parameter (default |
fit_prior |
If |
class_prior |
Numeric vector of length 2 with class probabilities,
used only when |
optimize_threshold |
If |
criterion |
One of |
tau_grid |
Either |
n_tau |
Number of grid points when |
K |
Number of CV folds. |
random_state |
Random seed for CV splits and CLT bootstrap. |
iterative |
If |
iter_mode |
|
p_iter, s_iter, clt_n_boot, clt_sample_size
|
Iterative refinement
parameters; see |
language_col |
Optional name of a column in |
x |
Alternative to |
y |
Alternative to |
doc_languages |
Optional character vector of per-document
language codes / names. Default and matrix interfaces only; same
purpose as |
Two interfaces are provided:
Formula + data.frame (idiomatic R):
itbnb(sentiment ~ text, data = reviews, ...)
where the right-hand side names a single column of data that
contains the raw text. The text is preprocessed internally with
quanteda according to the tbnb_preprocess() configuration.
Matrix / dfm + response (advanced / pipeline use):
itbnb(x = dfm, y = sentiment, ...)
where x is an already-built binary document-feature matrix
(any of: base matrix, Matrix sparse, quanteda::dfm, data.frame).
An object of class "tbnb" with components:
call, terms, xlevels, text_col, preprocess, embedding,
feature_names, classes, class_prior, class_occurrences,
feature_counts, log_pres, log_abs, alpha, threshold,
criterion, optimizer, iterative, decisions.
Romano M., Contu G., Mola F., Conversano C. (2024). doi:10.1007/s11634-023-00536-8
Romano M., Zammarchi G., Conversano C. (2024). doi:10.1007/s10260-023-00721-1
# Toy synthetic dataset (formula interface) reviews <- data.frame( sentiment = rep(c("pos", "neg"), each = 5), text = c( "great hotel friendly staff lovely view", "amazing room comfortable bed great breakfast", "wonderful stay clean rooms helpful staff", "fantastic location nice view comfortable", "lovely breakfast helpful staff great room", "dirty room rude staff terrible noise", "awful stay smelly room bad service", "noisy room rude reception dirty bathroom", "terrible breakfast cold food bad service", "horrible stay rude staff dirty noisy" ), stringsAsFactors = FALSE ) fit <- itbnb(sentiment ~ text, data = reviews, preprocess = tbnb_preprocess(language = "english", min_count = 1, min_docfreq = 1), K = 2, n_tau = 10, iterative = FALSE) predict(fit, newdata = reviews[1:3, ], type = "class") summary(fit)# Toy synthetic dataset (formula interface) reviews <- data.frame( sentiment = rep(c("pos", "neg"), each = 5), text = c( "great hotel friendly staff lovely view", "amazing room comfortable bed great breakfast", "wonderful stay clean rooms helpful staff", "fantastic location nice view comfortable", "lovely breakfast helpful staff great room", "dirty room rude staff terrible noise", "awful stay smelly room bad service", "noisy room rude reception dirty bathroom", "terrible breakfast cold food bad service", "horrible stay rude staff dirty noisy" ), stringsAsFactors = FALSE ) fit <- itbnb(sentiment ~ text, data = reviews, preprocess = tbnb_preprocess(language = "english", min_count = 1, min_docfreq = 1), K = 2, n_tau = 10, iterative = FALSE) predict(fit, newdata = reviews[1:3, ], type = "class") summary(fit)
Plot the distribution of decision scores by class
## S3 method for class 'tbnb' plot(x, newdata = NULL, y = NULL, breaks = 40, ...)## S3 method for class 'tbnb' plot(x, newdata = NULL, y = NULL, breaks = 40, ...)
x |
A fitted |
newdata |
Optional data to score (default: scores cannot be
recovered from the model alone, so |
y |
Optional response vector aligned with |
breaks |
Histogram breaks. |
... |
Additional graphical parameters. |
Invisibly, the numeric vector of decision scores computed for
newdata, or NULL when newdata is not supplied. The function is
called for its side effect of drawing the score distribution together
with the estimated threshold(s).
tbnb modelPredictions from a fitted tbnb model
## S3 method for class 'tbnb' predict( object, newdata, type = c("class", "score", "prob", "raw"), threshold = NULL, iterative = NULL, doc_languages = NULL, ... )## S3 method for class 'tbnb' predict( object, newdata, type = c("class", "score", "prob", "raw"), threshold = NULL, iterative = NULL, doc_languages = NULL, ... )
object |
A fitted model of class |
newdata |
Either a |
type |
One of:
|
threshold |
Optional override for the decision threshold
(default: the one stored in |
iterative |
Optional logical to override |
doc_languages |
Optional character vector of per-document language
codes / names for |
... |
Currently unused. |
A vector of the requested type.
Summary of a fitted Tb-NB / iTb-NB model
## S3 method for class 'tbnb' summary( object, pvalues = FALSE, pvalue_method = c("clt", "kde"), pvalue_alpha = 0.05, ... )## S3 method for class 'tbnb' summary( object, pvalues = FALSE, pvalue_method = c("clt", "kde"), pvalue_alpha = 0.05, ... )
object |
A fitted |
pvalues |
If |
pvalue_method |
Either |
pvalue_alpha |
Significance level used to flag features. |
... |
Passed on. |
An object of class "tbnb_summary": a list collecting the class
labels, the vocabulary size, the class priors, the Laplace smoothing
parameter, the selection criterion and the estimated threshold, the
most positive and most negative words, the cross-validated
threshold-per-criterion table and, when pvalues = TRUE, the
feature-level p-value table. A print method is provided.
itbnb() for threshold optimisationNames of the criteria supported by itbnb() for threshold optimisation
tbnb_available_criteria()tbnb_available_criteria()
Character vector of criterion names.
Produces a partition of the model vocabulary into a finite set of
user-meaningful categories that can then be fed into
tbnb_posthoc_plots() for the post-hoc analyses described in
Romano et al. (2024) — e.g. how the sentiment of food, staff,
cleanliness etc. evolves over time, or differs across hotels.
tbnb_categorize( object, method = c("dbscan", "seed", "kmeans", "manual"), seeds = NULL, k = NULL, eps = NULL, minPts = 5L, n_categories_target = 10L, min_category_size = 5L, assignments = NULL, embedding = NULL, text_corpus = NULL, embedding_dim = 50L, embedding_iter = 15L, embedding_window = 5L, refine = FALSE, min_similarity = 0, features = NULL, hotel_reviews = FALSE, verbose = TRUE )tbnb_categorize( object, method = c("dbscan", "seed", "kmeans", "manual"), seeds = NULL, k = NULL, eps = NULL, minPts = 5L, n_categories_target = 10L, min_category_size = 5L, assignments = NULL, embedding = NULL, text_corpus = NULL, embedding_dim = 50L, embedding_iter = 15L, embedding_window = 5L, refine = FALSE, min_similarity = 0, features = NULL, hotel_reviews = FALSE, verbose = TRUE )
object |
A fitted |
method |
One of |
seeds |
For |
k |
For |
eps, minPts
|
For |
n_categories_target |
For |
min_category_size |
Categories with fewer than |
assignments |
For |
embedding |
Optional. Pre-trained word vectors as a numeric
matrix with row names = tokens, or a |
text_corpus |
Optional character vector of training texts used
to train a GloVe embedding when |
embedding_dim, embedding_iter, embedding_window
|
text2vec GloVe hyperparameters (used only when training on-the-fly). |
refine |
For |
min_similarity |
For |
features |
Optional character vector to restrict categorisation
to a subset of the model vocabulary. Default: all features in
|
hotel_reviews |
Logical (default |
verbose |
Print progress messages. |
Four methods are supported:
method = "seed" (semi-supervised). The user supplies a named list of
seed words per category; each remaining vocabulary word is assigned
to the category whose centroid (mean of seed vectors) is closest in
the embedding space (cosine similarity). With refine = TRUE the
procedure iterates k-means-style by recomputing centroids from the
current assignments until convergence.
method = "kmeans" (unsupervised, K chosen). Standard k-means on
the word vectors. Clusters are named cluster_1, ..., cluster_K.
method = "dbscan" (unsupervised, K automatic). Density-based
clustering with eps and minPts. Noise points are sent to the
special category "uncategorized". Requires the
dbscan package.
method = "manual". The user passes a named character vector
(words -> category) or a data.frame with columns word, category.
No clustering is performed.
For the three embedding-based methods, the user may supply a
pre-trained embedding (embedding =); otherwise a GloVe model is
trained on the fly on text_corpus using text2vec.
An S3 object of class "tbnb_categorization" with components:
assignments — data.frame(word, category, log_odds, similarity)
(the similarity column is NA for manual / dbscan / kmeans).
categories — character vector of category names.
method — the method used.
centroids — for seed / kmeans: matrix of category centroids.
embedding_used — the embedding matrix actually used (or NULL).
Romano M., Contu G., Mola F., Conversano C. (2024). Threshold-based Naive Bayes classifier. Advances in Data Analysis and Classification, 18, 325–361. doi:10.1007/s11634-023-00536-8
data(toy_reviews) fit <- itbnb(sentiment ~ text, data = toy_reviews, preprocess = tbnb_preprocess(language = "english")) # Manual categorisation (no embedding required) cat_man <- tbnb_categorize( fit, method = "manual", assignments = c(staff = "service", room = "room", breakfast = "food", view = "view")) print(cat_man)data(toy_reviews) fit <- itbnb(sentiment ~ text, data = toy_reviews, preprocess = tbnb_preprocess(language = "english")) # Manual categorisation (no embedding required) cat_man <- tbnb_categorize( fit, method = "manual", assignments = c(staff = "service", room = "room", breakfast = "food", view = "view")) print(cat_man)
At fit / predict time, for each token in a document, the
top-k most similar tokens in the embedding space are added to the
document with weight 1 (presence). This enriches the Bag-of-Words with
synonyms / semantic neighbours, which can help mitigate sparsity issues
and out-of-vocabulary problems while leaving the Tb-NB
word-interpretability intact.
tbnb_embedding(vectors, k = 3L, min_similarity = 0.5, self_include = TRUE)tbnb_embedding(vectors, k = 3L, min_similarity = 0.5, self_include = TRUE)
vectors |
Either:
|
k |
Number of nearest semantic neighbours to add per token. |
min_similarity |
Minimum cosine similarity to keep a neighbour. |
self_include |
Whether to keep the original token itself among the
neighbours (it would otherwise always be the top-1 with similarity 1).
Should usually be |
This is an extension not present in the original Tb-NB / iTb-NB
papers. It is disabled by default and must be explicitly enabled by
passing the returned configuration to the embedding argument of
itbnb().
A tbnb_embedding configuration object.
Returns the 12 reference categories used in the Booking.com analysis
of Romano et al. (2024) — cleaning, comfort, position,
price-quality-rate, services, staff, wifi, bar, food, hotel, room,
sleep-quality — each populated with bilingual Italian + English
seed words. The 13th category from the paper, "other", is the
residual one and is handled automatically as "uncategorized".
tbnb_hospitality_seeds()tbnb_hospitality_seeds()
Used by tbnb_categorize() when hotel_reviews = TRUE.
A named list of character vectors (one per category).
Starting from a global threshold tau, the algorithm iteratively
inspects the uncertainty region around it and proposes a refined local
threshold by estimating the intersection of the two class-conditional
score densities. The refinement is repeated until convergence, lack of
data, or until the modes of the two densities become indistinguishable.
tbnb_iterate( scores, y, tau, p = 0.2, s = 20L, mode = c("kde", "clt"), clt_boot = 500L, clt_sample = 30L, epsilon = 0.001, max_iter = 50L )tbnb_iterate( scores, y, tau, p = 0.2, s = 20L, mode = c("kde", "clt"), clt_boot = 500L, clt_sample = 30L, epsilon = 0.001, max_iter = 50L )
scores |
Numeric vector of Tb-NB scores. |
y |
Binary labels in |
tau |
Initial global threshold. |
p |
Fraction of samples around |
s |
Minimum sample count required to keep iterating.
In |
mode |
|
clt_boot, clt_sample
|
CLT bootstrap settings, ignored when
|
epsilon |
Convergence tolerance both on |
max_iter |
Hard upper bound on iteration count (safety net). |
A data.frame of decisions, one row per refinement step, with
columns:
iteration, start, end, tau, x_max_pos, x_max_neg,
direction ("r" if positive class mode is to the right of negative,
"l" otherwise).
Compute all binary classification metrics from confusion counts
tbnb_metrics(TP, FP, TN, FN)tbnb_metrics(TP, FP, TN, FN)
TP, TN, FP, FN
|
Confusion counts (scalars or vectors of equal length). |
A named list with the metrics listed in
tbnb_available_criteria().
Given an already-fitted Tb-NB model and the training data used to fit it,
explores a grid of candidate thresholds and reports the best
value for each available criterion.
tbnb_optimize_threshold( X, y, alpha = 1, fit_prior = TRUE, class_prior = NULL, tau_grid = "observed", n_tau = 50L, K = 5L, random_state = 42L )tbnb_optimize_threshold( X, y, alpha = 1, fit_prior = TRUE, class_prior = NULL, tau_grid = "observed", n_tau = 50L, K = 5L, random_state = 42L )
X |
Binary sparse matrix (presence / absence of features). |
y |
Integer response in |
alpha |
Laplace smoothing parameter. |
fit_prior, class_prior
|
See |
tau_grid |
Either |
n_tau |
Grid size when |
K |
Number of CV folds. |
random_state |
Random seed. |
List with components:
tau_grid – sorted grid of candidate thresholds;
metric_mats – named list of K x n_tau matrices, one per metric;
best_tau – named numeric vector of optimal per criterion.
Combines the per-word sentiment scores from a fitted Tb-NB / iTb-NB
model with a categorisation produced by tbnb_categorize() to
generate the post-hoc plots described in Romano et al. (2024) —
i.e. how each category contributes to overall sentiment, how
sentiment evolves over time, which words are statistically
significant within each category, etc.
tbnb_posthoc_plots( object, categorization, newdata, time_var = NULL, group_var = NULL, doc_languages = NULL, pvalues = NULL, which = c("category_score", "time_series", "feature_volcano", "category_distribution", "top_words_per_category"), top_n_words = 15L, exclude_words = NULL, exclude_top_quantile = NULL, exclude_carriers = FALSE, time_unit = c("month", "quarter", "year", "week"), palette = NULL, theme = "minimal" )tbnb_posthoc_plots( object, categorization, newdata, time_var = NULL, group_var = NULL, doc_languages = NULL, pvalues = NULL, which = c("category_score", "time_series", "feature_volcano", "category_distribution", "top_words_per_category"), top_n_words = 15L, exclude_words = NULL, exclude_top_quantile = NULL, exclude_carriers = FALSE, time_unit = c("month", "quarter", "year", "week"), palette = NULL, theme = "minimal" )
object |
A fitted |
categorization |
A |
newdata |
Data on which to compute document-level scores
(typically the training or test set). Either a |
time_var |
Name of a column of |
group_var |
Optional name of a column of |
doc_languages |
Optional per-document language vector
(see |
pvalues |
Optional output of |
which |
Subset of plots to compute; any of
|
top_n_words |
Number of word labels shown in the volcano and the per-category top-words plot. |
exclude_words |
Optional character vector of words to drop from all post-hoc plots. Useful for sentiment carriers such as bellissimo, consigliatissimo, orribile that are useful for classification but uninformative for category-level analysis. |
exclude_top_quantile |
Numeric in |
exclude_carriers |
Logical. If |
time_unit |
How to bucket the timestamps for the time-series
plot: |
palette |
Optional vector of category colours (length equal to
the number of categories). When |
theme |
Either a |
The returned list contains ggplot2 objects so the user can
further customise them, save them to disk via ggplot2::ggsave(),
or arrange them in panels.
A named list of ggplot objects (the keys are the entries
of which).
Romano M., Contu G., Mola F., Conversano C. (2024). Threshold-based Naive Bayes classifier. Advances in Data Analysis and Classification, 18, 325–361. doi:10.1007/s11634-023-00536-8
Helper used to build a configuration list to be passed to itbnb() via
the preprocess argument. The pipeline is implemented on top of
quanteda and produces a binary document-feature matrix that is fed
to the Tb-NB core.
tbnb_preprocess( language = "english", lowercase = TRUE, remove_punct = TRUE, remove_numbers = TRUE, remove_symbols = TRUE, remove_url = TRUE, remove_stopwords = TRUE, extra_stopwords = NULL, stem = FALSE, stem_language = NULL, detect_engine = c("cld2", "cld3"), min_word_length = 2L, min_count = 1L, min_docfreq = 1L, min_words_per_doc = 3L, ngrams = 1L )tbnb_preprocess( language = "english", lowercase = TRUE, remove_punct = TRUE, remove_numbers = TRUE, remove_symbols = TRUE, remove_url = TRUE, remove_stopwords = TRUE, extra_stopwords = NULL, stem = FALSE, stem_language = NULL, detect_engine = c("cld2", "cld3"), min_word_length = 2L, min_count = 1L, min_docfreq = 1L, min_words_per_doc = 3L, ngrams = 1L )
language |
Character. One or more language names accepted by
stopwords (e.g. |
lowercase |
Logical. Convert text to lowercase before tokenisation. |
remove_punct |
Logical. Drop punctuation tokens. |
remove_numbers |
Logical. Drop numeric tokens. |
remove_symbols |
Logical. Drop symbol tokens. |
remove_url |
Logical. Drop URL tokens. |
remove_stopwords |
Logical. Drop stopwords for the language(s)
in |
extra_stopwords |
Optional character vector with extra stopwords. |
stem |
Deprecated boolean. Use |
stem_language |
|
detect_engine |
Engine used when |
min_word_length |
Minimum number of characters per token kept. |
min_count, min_docfreq
|
Pruning of rare features. Tokens that appear
fewer than |
min_words_per_doc |
Minimum number of informative tokens
(counted after stopword removal and |
ngrams |
Integer vector with n-gram sizes to keep (default
|
The function supports both monolingual and multilingual corpora:
set language to a vector of language names (e.g.
c("italian", "english")) and the union of the corresponding stopword
lists will be removed. Stemming, which is language-specific, is
controlled by stem_language:
stem_language = NULL (default) — no stemming.
stem_language = "<lang>" — apply the Snowball stemmer for that
language to every token (a sensible default when one language
dominates the corpus; tokens from the minority language are stemmed
with the "wrong" rules but in practice this is rarely harmful).
stem_language = "per_document" — detect the language of each
document with cld2 or cld3 (see detect_engine) and
stem each document with the appropriate Snowball stemmer. Only
documents detected as one of the languages in language are
stemmed; documents detected as another language (or undetected) are
left as-is.
The legacy boolean stem = TRUE is still accepted for back-compat: it
is interpreted as stem_language = language[1].
A named list of class "tbnb_preprocess" to be supplied to
itbnb().
Implements the p-value extension introduced in Romano (2025) for the
Tb-NB / iTb-NB classifier. Two flavours are exposed via the type
argument:
tbnb_pvalues( object, type = c("document", "feature"), newdata = NULL, method = c("clt", "kde"), alpha = 0.05, n_boot = 500L, sample_size = 30L, two_sided = NULL )tbnb_pvalues( object, type = c("document", "feature"), newdata = NULL, method = c("clt", "kde"), alpha = 0.05, n_boot = 500L, sample_size = 30L, two_sided = NULL )
object |
A fitted |
type |
Either |
newdata |
Required when |
method |
Either |
alpha |
Significance level used to flag features in the
|
n_boot |
Number of bootstrap resamples for |
sample_size |
Sample size of each bootstrap draw for
|
two_sided |
If |
type = "document" — for each row of newdata, the per-class p-value
of the observed log-likelihood ratio score under the
training-set score distribution of each class ( and
). The two p-values are one-sided in the direction of class
membership, so that small p_pos flags strong evidence against the
"negative" hypothesis (i.e. evidence that the document is positive) and
vice-versa.
type = "feature" — for each token in the vocabulary, the two-sided
p-value of its log-odds against the distribution of
log-odds across all features under the null hypothesis of "no
discrimination" (vocabulary-wide reference distribution).
Two reference-distribution estimators are supported:
method = "clt" — bootstrap means with Normal approximation (Central
Limit Theorem). This is the procedure proposed in the paper and
yields more stable results.
method = "kde" — Gaussian kernel density estimate of the training
distribution, with p-values computed by numerical integration via
stats::approx().
An object of class tbnb_pvalues (a data.frame with attributes).
Romano, M. (2025). Iterative Threshold-based Naive Bayes classifier: further interpretability with p-values. In E. di Bella, V. Gioia, C. Lagazio & S. Zaccarin (Eds.), Statistics for Innovation I: SIS 2025, Short Papers, Plenary, Specialized, and Solicited Sessions (Chap. 41). Italian Statistical Society Series on Advances in Statistics. Springer, Cham. doi:10.1007/978-3-031-96736-8_41
data(toy_reviews) fit <- itbnb(sentiment ~ text, data = toy_reviews, preprocess = tbnb_preprocess(language = "english")) # Document-level p-values pv_doc <- tbnb_pvalues(fit, type = "document", newdata = toy_reviews, method = "clt") head(pv_doc) # Feature-level p-values pv_feat <- tbnb_pvalues(fit, type = "feature", method = "clt") head(pv_feat[order(pv_feat$p_value), ], 10)data(toy_reviews) fit <- itbnb(sentiment ~ text, data = toy_reviews, preprocess = tbnb_preprocess(language = "english")) # Document-level p-values pv_doc <- tbnb_pvalues(fit, type = "document", newdata = toy_reviews, method = "clt") head(pv_doc) # Feature-level p-values pv_feat <- tbnb_pvalues(fit, type = "feature", method = "clt") head(pv_feat[order(pv_feat$p_value), ], 10)
A small, hand-crafted dataset of 200 short fictional hotel reviews labelled as positive or negative. It is meant exclusively for illustration and unit tests; the wording is intentionally simple so that the Tb-NB classifier behaves intuitively on it.
toy_reviewstoy_reviews
A data.frame with 200 rows and 2 columns:
Factor with two levels "neg" and "pos".
Character. The (short) review text.
Synthetic data generated by the package authors. Inspired by the Booking.com reviews used in Romano et al. (2024).