onehot: Convert vector to a onehot representation (binary class...

Description Usage Arguments Value See Also Examples

View source: R/onehot.R

Description

Convert vector to a onehot representation (binary class matrix)

Usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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

 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
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)

listarrays documentation built on March 26, 2020, 6:10 p.m.