onehot_with_decoder {listarrays}R Documentation

Convert vector to a onehot representation (binary class matrix)

Description

Convert vector to a onehot representation (binary class matrix)

Usage

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

keras::to_categorical

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)

# 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)
decode_onehot(Y)

# factor and numeric vectors also accepted
onehot(factor(letters[1:4]))
onehot(4:8)


[Package listarrays version 0.4.0 Index]