CategoryEncoding converts integer category indices into encoded representations, typically completing a categorical preprocessing pipeline after StringLookup or IntegerLookup. section 9.3.2
Listing 9.13 Creating encoding layers for categorical columns
# function from
https://www.tensorflow.org/tutorials/structured_data/preprocessing_layers
def get_category_encoding_layer(name, dataset, dtype, max_tokens=None):
if dtype == 'string': #1
index = layers.StringLookup(max_tokens=max_tokens)
else:
index = layers.IntegerLookup(max_tokens=max_tokens)
feature_ds = dataset.map(lambda x, y: x[name]) #2
index.adapt(feature_ds) #3
encoder = \
layers.CategoryEncoding(num_tokens= \
index.vocabulary_size()) #4
return lambda feature: encoder(index(feature)) #5
Build the encoder by adapting a lookup layer to a dataset, sizing CategoryEncoding from the vocabulary, and composing both transformations. section 9.3.2
Encoding real-estate categories
A Kuala Lumpur property model gives each categorical column an input, lookup layer, and CategoryEncoding layer before concatenating encoded features with normalized continuous columns. One-hot encoding fits columns with roughly 100 or fewer unique values, while very large vocabularies may require embeddings to avoid memory problems. section 9.3.2
