Skip to contents

Encodes a high-cardinality factor by each level's actual-to-expected ratio, shrunk to 1 by the credibility z = n / (n + k) with n the level's exposure: z A / E + (1 - z) (CAS Monograph 16, chapter 6). Each training row is encoded from the other folds only, so its own response never enters its encoding; encode_target() applies the encoding from all the rows to new data (a level not seen in training gets 1). Its log enters a GLM as a numeric column.

Usage

target_encode(values, y, expected, splits, k, exposure = NULL)

encode_target(encoding, newvalues)

Arguments

values

The factor's level per row.

y

Actual responses.

expected

Expected responses: the overall mean times exposure, or a first model's predictions.

splits

Splits from k_fold() or group_k_fold(), every row in exactly one test set.

k

The credibility constant.

exposure

Optional credibility weights, 1 per row by default.

encoding

A target_encoding list from target_encode().

newvalues

Levels of new data.

Value

target_encode() a list with rows (the out-of-fold encoding of each training row) and encoding (a data frame of level and ratio, with k); encode_target() one value per new value.

Examples

splits <- list(list(train = c(2, 4), test = c(1, 3)), list(train = c(1, 3), test = c(2, 4)))
te <- target_encode(c("a", "a", "b", "b"), c(2, 2, 0, 1), rep(1, 4), splits, k = 1)
te$rows
#> [1] 1.5 1.5 1.0 0.5
encode_target(te$encoding, c("a", "z"))
#> [1] 1.666667 1.000000