ML Community Day is November 9! Join us for updates from TensorFlow, JAX, and more Learn more

tf.keras.layers.Hashing

Implements categorical feature hashing, also known as "hashing trick".

Inherits From: Layer, Module

Used in the notebooks

Used in the guide Used in the tutorials

This layer transforms single or multiple categorical inputs to hashed output. It converts a sequence of int or string to a sequence of int. The stable hash function uses tensorflow::ops::Fingerprint to produce the same output consistently across all platforms.

This layer uses FarmHash64 by default, which provides a consistent hashed output across different platforms and is stable across invocations, regardless of device and context, by mixing the input bits thoroughly.

If you want to obfuscate the hashed output, you can also pass a random salt argument in the constructor. In that case, the layer will use the SipHash64 hash function, with the salt value serving as additional input to the hash function.

Example (FarmHash64)

layer = tf.keras.layers.Hashing(num_bins=3)
inp = [['A'], ['B'], ['C'], ['D'], ['E']]
layer(inp)
<tf.Tensor: shape=(5, 1), dtype=int64, numpy=
  array([[1],
         [0],
         [1],
         [1],
         [2]])>

Example (FarmHash64) with a mask value

layer = tf.keras.layers.Hashing(num_bins=3, mask_value='')
inp = [['A'], ['B'], [''], ['C'], ['D']]
layer(inp)
<tf.Tensor: shape=(5, 1), dtype=int64, numpy=
  array([[1],
         [1],
         [0],
         [2],
         [2]])>

Example (SipHash64)

layer = tf.keras.layers.Hashing(num_bins=3, salt=[133, 137])
inp = [['A'], ['B'], ['C'], ['D'], ['E']]
layer(inp)
<tf.Tensor: shape=(5, 1), dtype=int64, numpy=
  array([[1],
         [2],
         [1],
         [0],
         [2]])>

Example (Siphash64 with a single integer, same as salt=[133, 133])