| Title: | Reproducible Text Classification Workflows |
|---|---|
| Description: | Dependency-light tools and tutorials for teaching reproducible text classification. The package covers HTML text extraction, sentence segmentation, text preprocessing, document-term matrices, TF-IDF, keyword extraction, cosine similarity, stratified cross-validation, classification metrics, and a multinomial Naive Bayes classifier. It modernizes the code accompanying Kobayashi, V. B., Berkers, H. A., Mol, S. T. Kismihok, G., and Den Hartog, D. N. (2017) <doi:10.1177/1094428117719322> The package replaces the original scripts in the paper. |
| Authors: | Vladimer Kobayashi [aut, cre], Stefan Mol [aut], Gabor Kismihok [aut] |
| Maintainer: | Vladimer Kobayashi <[email protected]> |
| License: | Apache License (>= 2) |
| Version: | 0.1.2 |
| Built: | 2026-09-26 09:58:28 UTC |
| Source: | https://github.com/cran/textclassificationtutorial |
Calculate binary classification metrics
classification_metrics(truth, estimate, positive)classification_metrics(truth, estimate, positive)
truth |
Vector of true classes. |
estimate |
Vector of predicted classes. |
positive |
Value identifying the positive class. |
A one-row data frame containing confusion counts, accuracy, balanced accuracy, precision, recall, specificity, and F1.
classification_metrics(c("task", "task", "other"), c("task", "other", "other"), positive = "task")classification_metrics(c("task", "task", "other"), c("task", "other", "other"), positive = "task")
Compute cosine similarity
cosine_similarity(x, y = NULL)cosine_similarity(x, y = NULL)
x |
Numeric matrix whose rows are observations. |
y |
Optional numeric matrix with the same columns as |
A numeric similarity matrix. Similarities involving zero vectors
are returned as NA.
x <- rbind(a = c(1, 1, 0), b = c(1, 0, 0), c = c(0, 0, 1)) cosine_similarity(x)x <- rbind(a = c(1, 1, 0), b = c(1, 0, 0), c = c(0, 0, 1)) cosine_similarity(x)
Construct a document-term matrix
document_term_matrix( text, document_ids = NULL, binary = FALSE, min_doc_freq = 1L, max_doc_prop = 1 )document_term_matrix( text, document_ids = NULL, binary = FALSE, min_doc_freq = 1L, max_doc_prop = 1 )
text |
Character vector containing one preprocessed document per item. |
document_ids |
Optional unique document identifiers. |
binary |
Logical; store term presence instead of term frequency? |
min_doc_freq |
Minimum number of documents in which a term must occur. |
max_doc_prop |
Maximum proportion of documents in which a term may occur. |
A numeric matrix with class text_dtm.
docs <- preprocess_text(c("data science", "data analysis", "science")) document_term_matrix(docs)docs <- preprocess_text(c("data science", "data analysis", "science")) document_term_matrix(docs)
Extract text from a directory of HTML files
extract_html_dir(path, pattern = "\\.html?$", recursive = FALSE, ...)extract_html_dir(path, pattern = "\\.html?$", recursive = FALSE, ...)
path |
Directory containing HTML files. |
pattern |
File-name regular expression. |
recursive |
Logical; search recursively? |
... |
Passed to |
A data frame with document_id, path, and text.
Extracts text from an HTML file or character string. When the suggested
xml2 package is installed, simple CSS selectors (tag, .class, #id,
or tag.class) or XPath can target a specific part of the page. A
dependency-free fallback strips markup from the full document.
extract_html_text( x, selector = NULL, xpath = NULL, collapse = "\n", trim = TRUE )extract_html_text( x, selector = NULL, xpath = NULL, collapse = "\n", trim = TRUE )
x |
Path to an HTML file or a length-one HTML character string. |
selector |
Optional CSS selector. |
xpath |
Optional XPath expression. Supply at most one of |
collapse |
Character used to join matched nodes. |
trim |
Logical; normalize whitespace and trim the result? |
A length-one character vector containing extracted text.
html <- "<html><body><h1>Analyst</h1><p>Analyze data.</p></body></html>" extract_html_text(html)html <- "<html><body><h1>Analyst</h1><p>Analyze data.</p></body></html>" extract_html_text(html)
Extract top TF-IDF keywords
extract_keywords(x, n = 1L, already_tfidf = FALSE)extract_keywords(x, n = 1L, already_tfidf = FALSE)
x |
A document-term matrix or TF-IDF matrix. |
n |
Number of keywords per document. |
already_tfidf |
Logical; is |
A data frame with document, rank, term, and weight.
F-measure
f_measure(precision, recall, beta = 1)f_measure(precision, recall, beta = 1)
precision |
Numeric precision. |
recall |
Numeric recall. |
beta |
Relative weight assigned to recall. |
Numeric F-measure.
Fit a multinomial Naive Bayes text classifier
fit_naive_bayes(x, y, laplace = 1, prior = NULL)fit_naive_bayes(x, y, laplace = 1, prior = NULL)
x |
Nonnegative numeric document-term matrix. |
y |
Class labels with one value per row of |
laplace |
Nonnegative additive smoothing parameter. |
prior |
Optional named class probabilities. |
An object of class text_nb.
x <- rbind(c(3, 0), c(2, 0), c(0, 3), c(0, 2)) colnames(x) <- c("analysis", "care") model <- fit_naive_bayes(x, c("data", "data", "health", "health")) predict(model, x)x <- rbind(c(3, 0), c(2, 0), c(0, 3), c(0, 2)) colnames(x) <- c("analysis", "care") model <- fit_naive_bayes(x, c("data", "data", "health", "health")) predict(model, x)
Normalize text for document-term analysis
preprocess_text( text, lowercase = TRUE, remove_punctuation = TRUE, remove_numbers = TRUE, stopwords = character(), min_token_length = 1L )preprocess_text( text, lowercase = TRUE, remove_punctuation = TRUE, remove_numbers = TRUE, stopwords = character(), min_token_length = 1L )
text |
Character vector. |
lowercase |
Logical; convert text to lowercase? |
remove_punctuation |
Logical; replace punctuation with spaces? |
remove_numbers |
Logical; replace digits with spaces? |
stopwords |
Optional character vector of words to remove. |
min_token_length |
Minimum number of characters per token. |
A character vector of normalized documents.
preprocess_text( c("Analyze the data!", "Present 2 reports."), stopwords = c("the") )preprocess_text( c("Analyze the data!", "Present 2 reports."), stopwords = c("the") )
Read a one-label-per-line file
read_label_file(path, type = c("character", "integer", "numeric", "factor"))read_label_file(path, type = c("character", "integer", "numeric", "factor"))
path |
Path to a text file. |
type |
Return labels as character, integer, numeric, or factor. |
A vector of labels.
A lightweight sentence segmenter suitable for tutorials and clean prose. It splits at terminal punctuation followed by whitespace, and optionally at line breaks and vertical bars. For production multilingual segmentation, use a dedicated NLP tokenizer.
split_sentences( text, split_lines = TRUE, keep_punctuation = TRUE, drop_empty = TRUE )split_sentences( text, split_lines = TRUE, keep_punctuation = TRUE, drop_empty = TRUE )
text |
Character vector. |
split_lines |
Logical; treat line breaks and |
keep_punctuation |
Logical; retain terminal punctuation? |
drop_empty |
Logical; remove empty results? |
A character vector of sentences.
split_sentences("Analyze data. Present results! Work with teams?")split_sentences("Analyze data. Present results! Work with teams?")
Create stratified cross-validation folds
stratified_folds(y, k = 5L, repeats = 1L, seed = NULL)stratified_folds(y, k = 5L, repeats = 1L, seed = NULL)
y |
Class labels. |
k |
Number of folds. |
repeats |
Number of repeated fold sets. |
seed |
Optional random seed. The caller's random-number state is restored. |
A list of integer test-set indices with class text_folds.
Calculate TF-IDF weights
tf_idf(dtm, normalize = c("length", "max", "none"), smooth_idf = TRUE)tf_idf(dtm, normalize = c("length", "max", "none"), smooth_idf = TRUE)
dtm |
Numeric document-term matrix. |
normalize |
Term-frequency normalization: document length, maximum frequency, or none. |
smooth_idf |
Logical; use smoothed inverse document frequency? |
A numeric matrix of TF-IDF weights.