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))
y | character, factor, or numeric vector |
---|---|
order |
|
named | if the returned matrix should have column names |
Y | a matrix, as returned by |
classes | A character vector of class names in the order corresponding
to |
n_classes | The total number of classes expected in |
A binary class matrix
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#> a b c d #> [1,] 1 0 0 0 #> [2,] 0 1 0 0 #> [3,] 0 0 1 0 #> [4,] 0 0 0 1onehot(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