Convert vector to a onehot representation (binary class matrix)

onehot_with_decoder(y, order = NULL, named = TRUE)

onehot(y, order = NULL, named = TRUE)

decode_onehot(
  Y,
  classes = colnames(Y),
  n_classes = ncol(Y) %||% length(classes)
)

onehot_decoder(Y, classes = colnames(Y), n_classes = length(classes))

Arguments

y

character, factor, or numeric vector

order

NULL, FALSE, or a character vector. If NULL (the default), then levels are sorted with sort(). If FALSE, then levels are taken in order of their first appearance in y. If a character vector, then order must contain all levels found in y.

named

if the returned matrix should have column names

Y

a matrix, as returned by onehot() or similar.

classes

A character vector of class names in the order corresponding to Y's onehot encoding. Typically, colnames(Y). if NULL, then the decoder returns the column number.

n_classes

The total number of classes expected in Y. Used for input checking in the returned decoder, also, to reconstruct the correct dimensions if the passed in Y is missing dim() attributes.

Value

A binary class matrix

See also

Examples

if(require(zeallot)) { y <- letters[1:4] c(Y, decode) %<-% onehot_with_decoder(y) Y decode(Y) identical(y, decode(Y)) decode(Y[2,,drop = TRUE]) decode(Y[2,,drop = FALSE]) decode(Y[2:3,]) rm(Y, decode) } # more peicemeal functions Y <- onehot(y) decode_onehot(Y)
#> [1] "a" "b" "c" "d"
# if you need to decode a matrix that lost colnames, # make your own decoder that remembers classes my_decode <- onehot_decoder(Y) colnames(Y) <- NULL my_decode(Y)
#> [1] "a" "b" "c" "d"
decode_onehot(Y)
#> [1] 1 2 3 4
# factor and numeric vectors also accepted onehot(factor(letters[1:4]))
#> a b c d #> [1,] 1 0 0 0 #> [2,] 0 1 0 0 #> [3,] 0 0 1 0 #> [4,] 0 0 0 1
onehot(4:8)
#> 4 5 6 7 8 #> [1,] 1 0 0 0 0 #> [2,] 0 1 0 0 0 #> [3,] 0 0 1 0 0 #> [4,] 0 0 0 1 0 #> [5,] 0 0 0 0 1