|
| 1 | +#' Text vectorization layer |
| 2 | +#' |
| 3 | +#' This layer has basic options for managing text in a Keras model. It |
| 4 | +#' transforms a batch of strings (one sample = one string) into either a list of |
| 5 | +#' token indices (one sample = 1D tensor of integer token indices) or a dense |
| 6 | +#' representation (one sample = 1D tensor of float values representing data about |
| 7 | +#' the sample's tokens). |
| 8 | +#' |
| 9 | +#' The processing of each sample contains the following steps: |
| 10 | +#' |
| 11 | +#' 1) standardize each sample (usually lowercasing + punctuation stripping) |
| 12 | +#' 2) split each sample into substrings (usually words) |
| 13 | +#' 3) recombine substrings into tokens (usually ngrams) |
| 14 | +#' 4) index tokens (associate a unique int value with each token) |
| 15 | +#' 5) transform each sample using this index, either into a vector of ints or |
| 16 | +#' a dense float vector. |
| 17 | +#' |
| 18 | +#' @inheritParams layer_dense |
| 19 | +#' @param max_tokens The maximum size of the vocabulary for this layer. If `NULL`, |
| 20 | +#' there is no cap on the size of the vocabulary. |
| 21 | +#' @param standardize Optional specification for standardization to apply to the |
| 22 | +#' input text. Values can be `NULL` (no standardization), |
| 23 | +#' `"lower_and_strip_punctuation"` (lowercase and remove punctuation) or a |
| 24 | +#' Callable. Default is `"lower_and_strip_punctuation"`. |
| 25 | +#' @param split Optional specification for splitting the input text. Values can be |
| 26 | +#' `NULL` (no splitting), `"split_on_whitespace"` (split on ASCII whitespace), or |
| 27 | +#' a Callable. Default is `"split_on_whitespace"`. |
| 28 | +#' @param ngrams Optional specification for ngrams to create from the possibly-split |
| 29 | +#' input text. Values can be `NULL`, an integer or a list of integers; passing |
| 30 | +#' an integer will create ngrams up to that integer, and passing a list of |
| 31 | +#' integers will create ngrams for the specified values in the list. Passing |
| 32 | +#' `NULL` means that no ngrams will be created. |
| 33 | +#' @param output_mode Optional specification for the output of the layer. Values can |
| 34 | +#' be `"int"`, `"binary"`, `"count"` or `"tfidf"`, which control the outputs as follows: |
| 35 | +#' * "int": Outputs integer indices, one integer index per split string token. |
| 36 | +#' * "binary": Outputs a single int array per batch, of either vocab_size or |
| 37 | +#' `max_tokens` size, containing 1s in all elements where the token mapped |
| 38 | +#' to that index exists at least once in the batch item. |
| 39 | +#' * "count": As "binary", but the int array contains a count of the number of |
| 40 | +#' times the token at that index appeared in the batch item. |
| 41 | +#' * "tfidf": As "binary", but the TF-IDF algorithm is applied to find the value |
| 42 | +#' in each token slot. |
| 43 | +#' @param output_sequence_length Only valid in "int" mode. If set, the output will have |
| 44 | +#' its time dimension padded or truncated to exactly `output_sequence_length` |
| 45 | +#' values, resulting in a tensor of shape (batch_size, output_sequence_length) regardless |
| 46 | +#' of how many tokens resulted from the splitting step. Defaults to `NULL`. |
| 47 | +#' @param pad_to_max_tokens Only valid in "binary", "count", and "tfidf" modes. If `TRUE`, |
| 48 | +#' the output will have its feature axis padded to `max_tokens` even if the |
| 49 | +#' number of unique tokens in the vocabulary is less than max_tokens, |
| 50 | +#' resulting in a tensor of shape (batch_size, max_tokens) regardless of |
| 51 | +#' vocabulary size. Defaults to `TRUE`. |
| 52 | +#' @param ... Not used. |
| 53 | +#' |
| 54 | +#' @export |
| 55 | +layer_text_vectorization <- function(object, max_tokens = NULL, standardize = "lower_and_strip_punctuation", |
| 56 | + split = "whitespace", ngrams = NULL, |
| 57 | + output_mode = c("int", "binary", "count", "tfidf"), |
| 58 | + output_sequence_length = NULL, pad_to_max_tokens = TRUE, |
| 59 | + ...) { |
| 60 | + |
| 61 | + if (tensorflow::tf_version() < "2.1") |
| 62 | + stop("Text Vectorization requires TensorFlow version >= 2.1", call. = FALSE) |
| 63 | + |
| 64 | + if (length(ngrams) > 1) |
| 65 | + ngrams <- as_integer_tuple(ngrams) |
| 66 | + else |
| 67 | + ngrams <- as_nullable_integer(ngrams) |
| 68 | + |
| 69 | + output_mode <- match.arg(output_mode) |
| 70 | + |
| 71 | + args <- list( |
| 72 | + max_tokens = as_nullable_integer(max_tokens), |
| 73 | + ngrams = ngrams, |
| 74 | + output_mode = output_mode, |
| 75 | + output_sequence_length = as_nullable_integer(output_sequence_length), |
| 76 | + pad_to_max_tokens = pad_to_max_tokens |
| 77 | + ) |
| 78 | + |
| 79 | + # see https://github.com/tensorflow/tensorflow/pull/34420 |
| 80 | + if (!identical(standardize, "lower_and_strip_punctuation")) |
| 81 | + args$standardize <- standardize |
| 82 | + |
| 83 | + if (!identical(split, "whitespace")) |
| 84 | + args$split <- split |
| 85 | + |
| 86 | + create_layer(resolve_text_vectorization_module(), object, args) |
| 87 | +} |
| 88 | + |
| 89 | +#' Get the vocabulary for text vectorization layers |
| 90 | +#' |
| 91 | +#' @param object a text vectorization layer |
| 92 | +#' |
| 93 | +#' @seealso [set_vocabulary()] |
| 94 | +#' @export |
| 95 | +get_vocabulary <- function(object) { |
| 96 | + object$get_vocabulary() |
| 97 | +} |
| 98 | + |
| 99 | +#' Sets vocabulary (and optionally document frequency) data for the layer |
| 100 | +#' |
| 101 | +#' This method sets the vocabulary and DF data for this layer directly, instead |
| 102 | +#' of analyzing a dataset through [adapt()]. It should be used whenever the `vocab` |
| 103 | +#' (and optionally document frequency) information is already known. If |
| 104 | +#' vocabulary data is already present in the layer, this method will either |
| 105 | +#' replace it, if `append` is set to `FALSE`, or append to it (if 'append' is set |
| 106 | +#' to `TRUE`) |
| 107 | +#' |
| 108 | +#' @inheritParams get_vocabulary |
| 109 | +#' @param vocab An array of string tokens. |
| 110 | +#' @param df_data An array of document frequency data. Only necessary if the layer |
| 111 | +#' output_mode is "tfidf". |
| 112 | +#' @param oov_df_value The document frequency of the OOV token. Only necessary if |
| 113 | +#' output_mode is "tfidf". OOV data is optional when appending additional |
| 114 | +#' data in "tfidf" mode; if an OOV value is supplied it will overwrite the |
| 115 | +#' existing OOV value. |
| 116 | +#' @param append Whether to overwrite or append any existing vocabulary data. |
| 117 | +#' |
| 118 | +#' @seealso [get_vocabulary()] |
| 119 | +#' |
| 120 | +#' @export |
| 121 | +set_vocabulary <- function(object, vocab, df_data = NULL, oov_df_value = FALSE, |
| 122 | + append = FALSE) { |
| 123 | + object$set_vocabulary(vocab, df_data, oov_df_value, append) |
| 124 | +} |
| 125 | + |
| 126 | + |
| 127 | +resolve_text_vectorization_module <- function() { |
| 128 | + if (keras_version() >= "2.2.4") |
| 129 | + keras$layers$experimental$preprocessing$TextVectorization |
| 130 | + else |
| 131 | + stop("Keras >= 2.2.4 is required", call. = FALSE) |
| 132 | +} |
0 commit comments