# tf.keras.layers.Discretization

<br />

|---|
| [![](https://www.tensorflow.org/images/GitHub-Mark-32px.png) View source on GitHub](https://github.com/keras-team/keras/tree/v2.7.0/keras/layers/preprocessing/discretization.py#L123-L289) |

A preprocessing layer which buckets continuous features by ranges.

Inherits From: [`PreprocessingLayer`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/keras/layers/experimental/preprocessing/PreprocessingLayer), [`Layer`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/keras/layers/Layer), [`Module`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/Module)

#### View aliases


**Main aliases**

[`tf.keras.layers.experimental.preprocessing.Discretization`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Discretization)
**Compat aliases for migration**

See
[Migration guide](https://www.tensorflow.org/guide/migrate) for
more details.

[`tf.compat.v1.keras.layers.Discretization`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Discretization), [`tf.compat.v1.keras.layers.experimental.preprocessing.Discretization`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Discretization)

<br />

    tf.keras.layers.Discretization(
        bin_boundaries=None, num_bins=None, epsilon=0.01, **kwargs
    )

This layer will place each element of its input data into one of several
contiguous ranges and output an integer index indicating which range each
element was placed in.

For an overview and full list of preprocessing layers, see the preprocessing
[guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

<br />

<br />

<br />

| ## Input shape ||
|---|---|
| Any [`tf.Tensor`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/Tensor) or [`tf.RaggedTensor`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/RaggedTensor) of dimension 2 or higher. ||

<br />

<br />

<br />

<br />

| ## Output shape ||
|---|---|
| Same as input shape. ||

<br />

#### Examples:

Bucketize float values based on provided buckets.

    >>> input = np.array([[-1.5, 1.0, 3.4, .5], [0.0, 3.0, 1.3, 0.0]])
    >>> layer = tf.keras.layers.Discretization(bin_boundaries=[0., 1., 2.])
    >>> layer(input)
    <tf.Tensor: shape=(2, 4), dtype=int64, numpy=
    array([[0, 2, 3, 1],
           [1, 3, 2, 1]], dtype=int64)>

Bucketize float values based on a number of buckets to compute.

    >>> input = np.array([[-1.5, 1.0, 3.4, .5], [0.0, 3.0, 1.3, 0.0]])
    >>> layer = tf.keras.layers.Discretization(num_bins=4, epsilon=0.01)
    >>> layer.adapt(input)
    >>> layer(input)
    <tf.Tensor: shape=(2, 4), dtype=int64, numpy=
    array([[0, 2, 3, 2],
           [1, 3, 3, 1]], dtype=int64)>

<br />

<br />

<br />

| ## Attributes ||
|---|---|
| `bin_boundaries` | A list of bin boundaries. The leftmost and rightmost bins will always extend to `-inf` and `inf`, so `bin_boundaries=[0., 1., 2.]` generates bins `(-inf, 0.)`, `[0., 1.)`, `[1., 2.)`, and `[2., +inf)`. If this option is set, `adapt` should not be called. |
| `num_bins` | The integer number of bins to compute. If this option is set, `adapt` should be called to learn the bin boundaries. |
| `epsilon` | Error tolerance, typically a small fraction close to zero (e.g. 0.01). Higher values of epsilon increase the quantile approximation, and hence result in more unequal buckets, but could improve performance and resource consumption. |
| `is_adapted` | Whether the layer has been fit to data already. |

<br />

## Methods

### `adapt`

[View source](https://github.com/keras-team/keras/tree/v2.7.0/keras/engine/base_preprocessing_layer.py#L156-L248)

    adapt(
        data, batch_size=None, steps=None
    )

Fits the state of the preprocessing layer to the data being passed.

After calling `adapt` on a layer, a preprocessing layer's state will not
update during training. In order to make preprocessing layers efficient in
any distribution context, they are kept constant with respect to any
compiled [`tf.Graph`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/Graph)s that call the layer. This does not affect the layer use
when adapting each layer only once, but if you adapt a layer multiple times
you will need to take care to re-compile any compiled functions as follows:

- If you are adding a preprocessing layer to a [`keras.Model`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/keras/Model), you need to call `model.compile` after each subsequent call to `adapt`.
- If you are calling a preprocessing layer inside [`tf.data.Dataset.map`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/data/Dataset#map), you should call `map` again on the input [`tf.data.Dataset`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/data/Dataset) after each `adapt`.
- If you are using a [`tf.function`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/function) directly which calls a preprocessing layer, you need to call [`tf.function`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/function) again on your callable after each subsequent call to `adapt`.

[`tf.keras.Model`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/keras/Model) example with multiple adapts:

    layer = tf.keras.layers.experimental.preprocessing.Normalization(
        axis=None)
    layer.adapt([0, 2])
    model = tf.keras.Sequential(layer)
    model.predict([0, 1, 2])
    array([-1.,  0.,  1.], dtype=float32)
    layer.adapt([-1, 1])
    model.compile() # This is needed to re-compile model.predict!
    model.predict([0, 1, 2])
    array([0., 1., 2.], dtype=float32)

[`tf.data.Dataset`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/data/Dataset) example with multiple adapts:

    layer = tf.keras.layers.experimental.preprocessing.Normalization(
        axis=None)
    layer.adapt([0, 2])
    input_ds = tf.data.Dataset.range(3)
    normalized_ds = input_ds.map(layer)
    list(normalized_ds.as_numpy_iterator())
    [array([-1.], dtype=float32),
     array([0.], dtype=float32),
     array([1.], dtype=float32)]
    layer.adapt([-1, 1])
    normalized_ds = input_ds.map(layer) # Re-map over the input dataset.
    list(normalized_ds.as_numpy_iterator())
    [array([0.], dtype=float32),
     array([1.], dtype=float32),
     array([2.], dtype=float32)]

<br />

<br />

<br />

| Arguments ||
|---|---|
| `data` | The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. |
| `batch_size` | Integer or `None`. Number of samples per state update. If unspecified, `batch_size` will default to 32. Do not specify the `batch_size` if your data is in the form of datasets, generators, or [`keras.utils.Sequence`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/keras/utils/Sequence) instances (since they generate batches). |
| `steps` | Integer or `None`. Total number of steps (batches of samples) When training with input tensors such as TensorFlow data tensors, the default `None` is equal to the number of samples in your dataset divided by the batch size, or 1 if that cannot be determined. If x is a [`tf.data`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/data) dataset, and 'steps' is None, the epoch will run until the input dataset is exhausted. When passing an infinitely repeating dataset, you must specify the `steps` argument. This argument is not supported with array inputs. |

<br />

### `compile`

[View source](https://github.com/keras-team/keras/tree/v2.7.0/keras/engine/base_preprocessing_layer.py#L134-L154)

    compile(
        run_eagerly=None, steps_per_execution=None
    )

Configures the layer for `adapt`.

<br />

<br />

<br />

| Arguments ||
|---|---|
| `run_eagerly` | Bool. Defaults to `False`. If `True`, this `Model`'s logic will not be wrapped in a [`tf.function`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/function). Recommended to leave this as `None` unless your `Model` cannot be run inside a [`tf.function`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/function). steps_per_execution: Int. Defaults to 1. The number of batches to run during each [`tf.function`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/function) call. Running multiple batches inside a single [`tf.function`](https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/function) call can greatly improve performance on TPUs or small models with a large Python overhead. |

<br />

### `reset_state`

[View source](https://github.com/keras-team/keras/tree/v2.7.0/keras/layers/preprocessing/discretization.py#L243-L247)

    reset_state()

Resets the statistics of the preprocessing layer.

### `update_state`

[View source](https://github.com/keras-team/keras/tree/v2.7.0/keras/layers/preprocessing/discretization.py#L219-L233)

    update_state(
        data
    )

Accumulates statistics for the preprocessing layer.

<br />

<br />

<br />

| Arguments ||
|---|---|
| `data` | A mini-batch of inputs to the layer. |

<br />