/
sequence_onehot.R
289 lines (261 loc) · 7.62 KB
/
sequence_onehot.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#' Positional One-Hot encoding of Tokens
#'
#' `step_sequence_onehot()` creates a *specification* of a recipe step that will
#' take a string and do one hot encoding for each character by position.
#'
#' @template args-recipe
#' @template args-dots
#' @template args-role_predictors
#' @template args-trained
#' @template args-columns
#' @param sequence_length A numeric, number of characters to keep before
#' discarding. Defaults to 100.
#' @param padding 'pre' or 'post', pad either before or after each sequence.
#' defaults to 'pre'.
#' @param truncating 'pre' or 'post', remove values from sequences larger than
#' sequence_length either in the beginning or in the end of the sequence.
#' Defaults too 'pre'.
#' @param vocabulary A character vector, characters to be mapped to integers.
#' Characters not in the vocabulary will be encoded as 0. Defaults to
#' `letters`.
#' @param prefix A prefix for generated column names, defaults to "seq1hot".
#' @template args-keep_original_cols
#' @template args-skip
#' @template args-id
#'
#' @source
#' \url{https://papers.nips.cc/paper/5782-character-level-convolutional-networks-for-text-classification.pdf}
#'
#'
#' @template returns
#'
#' @details
#'
#' The string will be capped by the sequence_length argument, strings shorter
#' then sequence_length will be padded with empty characters. The encoding will
#' assign an integer to each character in the vocabulary, and will encode
#' accordingly. Characters not in the vocabulary will be encoded as 0.
#'
#' # Tidying
#'
#' When you [`tidy()`][tidy.recipe()] this step, a tibble is returned with
#' columns `terms`, `vocabulary`, `token`, and `id`:
#'
#' \describe{
#' \item{terms}{character, the selectors or variables selected}
#' \item{vocabulary}{integer, index}
#' \item{token}{character, text corresponding to the index}
#' \item{id}{character, id of this step}
#' }
#'
#' @template case-weights-not-supported
#'
#' @family Steps for Numeric Variables From Characters
#'
#' @examples
#' library(recipes)
#' library(modeldata)
#' data(tate_text)
#'
#' tate_rec <- recipe(~medium, data = tate_text) %>%
#' step_tokenize(medium) %>%
#' step_tokenfilter(medium) %>%
#' step_sequence_onehot(medium)
#'
#' tate_obj <- tate_rec %>%
#' prep()
#'
#' bake(tate_obj, new_data = NULL)
#'
#' tidy(tate_rec, number = 3)
#' tidy(tate_obj, number = 3)
#' @export
step_sequence_onehot <-
function(recipe,
...,
role = "predictor",
trained = FALSE,
columns = NULL,
sequence_length = 100,
padding = "pre",
truncating = "pre",
vocabulary = NULL,
prefix = "seq1hot",
keep_original_cols = FALSE,
skip = FALSE,
id = rand_id("sequence_onehot")) {
if (length(padding) != 1 || !(padding %in% c("pre", "post"))) {
rlang::abort("`padding` should be one of: 'pre', 'post'")
}
if (length(truncating) != 1 || !(truncating %in% c("pre", "post"))) {
rlang::abort("`truncating` should be one of: 'pre', 'post'")
}
add_step(
recipe,
step_sequence_onehot_new(
terms = enquos(...),
role = role,
trained = trained,
columns = columns,
sequence_length = sequence_length,
padding = padding,
truncating = truncating,
vocabulary = vocabulary,
prefix = prefix,
keep_original_cols = keep_original_cols,
skip = skip,
id = id
)
)
}
step_sequence_onehot_new <-
function(terms, role, trained, columns, sequence_length, padding, truncating,
vocabulary, prefix, keep_original_cols, skip, id) {
step(
subclass = "sequence_onehot",
terms = terms,
role = role,
trained = trained,
columns = columns,
sequence_length = sequence_length,
padding = padding,
truncating = truncating,
vocabulary = vocabulary,
prefix = prefix,
keep_original_cols = keep_original_cols,
skip = skip,
id = id
)
}
#' @export
prep.step_sequence_onehot <- function(x, training, info = NULL, ...) {
col_names <- recipes_eval_select(x$terms, training, info)
check_type(training[, col_names], types = "tokenlist")
token_list <- list()
for (col_name in col_names) {
token_list[[col_name]] <- x$vocabulary %||%
sort(get_unique_tokens(training[[col_name]]))
}
step_sequence_onehot_new(
terms = x$terms,
role = x$role,
trained = TRUE,
columns = col_names,
sequence_length = x$sequence_length,
padding = x$padding,
truncating = x$truncating,
vocabulary = token_list,
prefix = x$prefix,
keep_original_cols = get_keep_original_cols(x),
skip = x$skip,
id = x$id
)
}
#' @export
bake.step_sequence_onehot <- function(object, new_data, ...) {
col_names <- object$columns
check_new_data(col_names, object, new_data)
if (is.null(names(object$vocabulary))) {
# Backwards compatibility with 1.0.3 (#230)
names(object$vocabulary) <- col_names
}
for (col_name in col_names) {
out_text <- string2encoded_matrix(
x = new_data[[col_name]],
vocabulary = object$vocabulary[[col_name]],
sequence_length = object$sequence_length,
padding = object$padding,
truncating = object$truncating
)
colnames(out_text) <- paste(
sep = "_",
object$prefix,
col_name,
seq_len(ncol(out_text))
)
out_text <- as_tibble(out_text)
out_text <- check_name(out_text, new_data, object, names(out_text))
new_data <- vec_cbind(new_data, out_text)
}
new_data <- remove_original_cols(new_data, object, col_names)
new_data
}
#' @export
print.step_sequence_onehot <-
function(x, width = max(20, options()$width - 30), ...) {
title <- "Sequence 1 hot encoding for "
print_step(x$columns, x$terms, x$trained, title, width)
invisible(x)
}
#' @rdname step_sequence_onehot
#' @usage NULL
#' @export
tidy.step_sequence_onehot <- function(x, ...) {
if (is_trained(x)) {
if (length(x$columns) == 0) {
res <- tibble(
terms = character(),
vocabulary = character(),
token = integer()
)
} else {
res <- tibble(
terms = rep(x$columns, each = lengths(x$vocabulary)),
vocabulary = unlist(lapply(x$vocabulary, seq_along)),
token = unlist(x$vocabulary)
)
}
} else {
term_names <- sel2char(x$terms)
res <- tibble(
terms = term_names,
vocabulary = NA_character_,
token = NA_integer_
)
}
res$id <- x$id
res
}
char_key <- function(x) {
out <- seq_along(x)
names(out) <- x
out
}
string2encoded_matrix <- function(x, vocabulary, sequence_length, padding,
truncating) {
vocabulary <- char_key(vocabulary)
x <- get_tokens(x)
res <- matrix(NA_integer_, nrow = length(x), ncol = sequence_length)
for (i in seq_along(x)) {
len_x <- length(x[[i]])
values <- x[[i]]
if (len_x == 0) next
if (len_x == sequence_length) {
res[i, ] <- values
}
if (len_x < sequence_length) {
if (padding == "post") {
res[i, seq_len(len_x)] <- values
} else {
res[i, seq(sequence_length - len_x + 1, sequence_length)] <- values
}
} else {
if (truncating == "post") {
res[i, ] <- values[seq_len(sequence_length)]
} else {
res[i, ] <- values[seq(len_x - sequence_length + 1, len_x)]
}
}
}
res <- matrix(
vocabulary[match(res, names(vocabulary))],
nrow = length(x), ncol = sequence_length
)
res[is.na(res)] <- 0L
res
}
#' @rdname required_pkgs.step
#' @export
required_pkgs.step_sequence_onehot <- function(x, ...) {
c("textrecipes")
}