to_categorical: Converts a class vector (integers) to binary class matrix.

to_categoricalR Documentation

Converts a class vector (integers) to binary class matrix.

Description

E.g. for use with loss_categorical_crossentropy().

Usage

to_categorical(x, num_classes = NULL)

Arguments

x

Array-like with class values to be converted into a matrix (integers from 0 to num_classes - 1). R factors are coerced to integer and offset to be 0-based, i.e., as.integer(x) - 1L.

num_classes

Total number of classes. If NULL, this would be inferred as max(x) + 1. Defaults to NULL.

Value

A binary matrix representation of the input as an R array. The class axis is placed last.

Examples

a <- to_categorical(c(0, 1, 2, 3), num_classes=4)
print(a)
##      [,1] [,2] [,3] [,4]
## [1,]    1    0    0    0
## [2,]    0    1    0    0
## [3,]    0    0    1    0
## [4,]    0    0    0    1

b <- array(c(.9, .04, .03, .03,
              .3, .45, .15, .13,
              .04, .01, .94, .05,
              .12, .21, .5, .17),
              dim = c(4, 4))
loss <- op_categorical_crossentropy(a, b)
loss
## tf.Tensor([0.41284522 0.45601739 0.54430155 0.80437282], shape=(4), dtype=float64)

loss <- op_categorical_crossentropy(a, a)
loss
## tf.Tensor([1.00000005e-07 1.00000005e-07 1.00000005e-07 1.00000005e-07], shape=(4), dtype=float64)

See Also

Other numerical utils:
normalize()

Other utils:
audio_dataset_from_directory()
clear_session()
config_disable_interactive_logging()
config_disable_traceback_filtering()
config_enable_interactive_logging()
config_enable_traceback_filtering()
config_is_interactive_logging_enabled()
config_is_traceback_filtering_enabled()
get_file()
get_source_inputs()
image_array_save()
image_dataset_from_directory()
image_from_array()
image_load()
image_smart_resize()
image_to_array()
layer_feature_space()
normalize()
pack_x_y_sample_weight()
pad_sequences()
set_random_seed()
split_dataset()
text_dataset_from_directory()
timeseries_dataset_from_array()
unpack_x_y_sample_weight()
zip_lists()


rstudio/keras documentation built on April 22, 2024, 11:43 p.m.