Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Tensorflow Tfjs CategoryEncoding Layer

From Leeroopedia


Knowledge Sources
Domains Deep_Learning, Layers_API, Preprocessing
Last Updated 2026-02-10 06:00 GMT

Overview

The CategoryEncoding layer encodes integer categorical features into dense representations using one-hot, multi-hot, or count-based encoding. It validates that all input values are within the range [0, numTokens) and delegates to the shared encodeCategoricalInputs utility. This is a preprocessing layer designed to transform categorical input before feeding into downstream layers.

Code Reference

Source Location

tfjs-layers/src/layers/preprocessing/category_encoding.ts (GitHub)

Key Imports

import {LayerArgs, Layer} from '../../engine/topology';
import {serialization, Tensor, tidy, Tensor1D, Tensor2D} from '@tensorflow/tfjs-core';
import {greater, greaterEqual, max, min} from '@tensorflow/tfjs-core';
import * as utils from './preprocessing_utils';
import {OutputMode} from './preprocessing_utils';

Layer Class

export class CategoryEncoding extends Layer {
  static className = 'CategoryEncoding';
  constructor(args: CategoryEncodingArgs);
  override getConfig(): serialization.ConfigDict;
  override computeOutputShape(inputShape: Shape | Shape[]): Shape | Shape[];
  override call(inputs: Tensor | Tensor[], kwargs: Kwargs): Tensor[] | Tensor;
}

CategoryEncodingArgs

export interface CategoryEncodingArgs extends LayerArgs {
  numTokens: number;           // number of categories (vocabulary size)
  outputMode?: OutputMode;     // 'oneHot' | 'multiHot' | 'count' (default: 'multiHot')
}

Key Implementation Details

  • Input values are cast to int32 before processing.
  • Validates that all values satisfy 0 <= value < numTokens; throws ValueError otherwise.
  • Optional countWeights can be passed via kwargs when outputMode is 'count'.
  • For oneHot mode, an extra dimension is appended if the last dimension is not 1.

I/O Contract

Method Input Output
call Integer tensor with values in [0, numTokens) Encoded tensor with last dimension = numTokens
computeOutputShape Input shape Shape with last dim replaced by numTokens

Usage Example

import * as tf from '@tensorflow/tfjs';

const encoder = tf.layers.categoryEncoding({
  numTokens: 5,
  outputMode: 'oneHot'
});

const input = tf.tensor1d([0, 2, 4], 'int32');
const output = encoder.apply(input);
// output shape: [3, 5] with one-hot vectors

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment