<br />

|---|
| [![](https://www.tensorflow.org/images/GitHub-Mark-32px.png) View source on GitHub](https://github.com/tensorflow/tensorflow/blob/v2.21.0/tensorflow/python/ops/init_ops.py#L219-L394) |

Initializer that generates tensors with constant values.

#### View aliases


**Compat aliases for migration**

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

[`tf.compat.v1.initializers.constant`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/constant_initializer)

<br />

    tf.compat.v1.constant_initializer(
        value=0,
        dtype=https://www.tensorflow.org/api_docs/python/tf/dtypes#float32,
        verify_shape=False
    )

<br />

## Migrate to TF2

<br />

> [!CAUTION]
> **Caution:** This API was designed for TensorFlow v1. Continue reading for details on how to migrate from this API to a native TensorFlow v2 equivalent. See the [TensorFlow v1 to TensorFlow v2 migration guide](https://www.tensorflow.org/guide/migrate) for instructions on how to migrate the rest of your code.

Although it is a legacy API endpoint, [`tf.compat.v1.constant_initializer`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/constant_initializer)
is compatible with eager execution and [`tf.function`](https://www.tensorflow.org/api_docs/python/tf/function).

To migrate to a non-legacy TF2 API, please use [`tf.constant_initializer`](https://www.tensorflow.org/api_docs/python/tf/constant_initializer)
instead. The `dtype`
argument in [`tf.compat.v1.constantinitializer.init_()`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/constant_initializer#__init__) does not exist in
[`tf.constantinitializer.init_()`](https://www.tensorflow.org/api_docs/python/tf/constant_initializer#__init__). However, you can specify the `dtype` in
`__call__()` in both cases.

In the [`compat.v1`](https://www.tensorflow.org/api_docs/python/tf/compat/v1) symbol, if `verify_shape` is set to `True`, an exception
is raised when initializing a variable with a different shape from
`value`. If set to `False`, `value` is reshaped to initialize the variable
if necessary. An exception would only be raised when the number of
elements are different.

The `verify_shape` argument is not supported in TF2. Using
[`tf.constant_initializer`](https://www.tensorflow.org/api_docs/python/tf/constant_initializer) is equivalent to setting `verify_shape` to `False`.

#### Structural Mapping to TF2

Before:

    value = [0, 1, 2, 3, 4, 5, 6, 7]
    initializer = tf.compat.v1.constant_initializer(
        value=value,
        dtype=tf.float32,
        verify_shape=False)
    variable = tf.Variable(initializer(shape=[2, 4]))

After:

    value = [0, 1, 2, 3, 4, 5, 6, 7]
    initializer = tf.constant_initializer(value=value)
    tf.Variable(initializer(shape=[2, 4], dtype=tf.float32))

#### How to Map Arguments

| TF1 Arg Name | TF2 Arg Name | Note |
|---|---|---|
| `value` | `value` | In constructor |
| `dtype` | `dtype` | In `__call__()` method |
| `verify_shape` | Not Supported | Equivalent to set to `False` |
| `partition_info` | - | (`__call__` arg in TF1) Not supported |

#### Before \& After Usage Example

Before:

    value = [1., 2., 3., 4.]
    initializer = tf.compat.v1.constant_initializer(
        value=value, dtype=tf.float32, verify_shape=True)
    tf.Variable(initializer(shape=[2, 2])).numpy()
    Traceback (most recent call last):

    TypeError: Expected Tensor's shape: (2, 2), got (4,).
    initializer = tf.compat.v1.constant_initializer(
        value=value, dtype=tf.float32, verify_shape=False)
    tf.Variable(initializer(shape=[2, 2])).numpy()
    array([[1., 2.],
           [3., 4.]], dtype=float32)

After:

    value = [1., 2., 3., 4.]
    initializer = tf.constant_initializer(value=value)
    tf.Variable(initializer(shape=[2, 2], dtype=tf.float32)).numpy()
    array([[1., 2.],
           [3., 4.]], dtype=float32)

<br />

<br />

## Description

### Used in the notebooks

| Used in the guide |
|---|
| - [Migrating model checkpoints](https://www.tensorflow.org/guide/migrate/migrating_checkpoints) - [Use TF1.x models in TF2 workflows](https://www.tensorflow.org/guide/migrate/model_mapping) |

The resulting tensor is populated with values of type `dtype`, as
specified by arguments `value` following the desired `shape` of the
new tensor (see examples below).

The argument `value` can be a constant value, or a list of values of type
`dtype`. If `value` is a list, then the length of the list must be less
than or equal to the number of elements implied by the desired shape of the
tensor. In the case where the total number of elements in `value` is less
than the number of elements required by the tensor shape, the last element
in `value` will be used to fill the remaining entries. If the total number of
elements in `value` is greater than the number of elements required by the
tensor shape, the initializer will raise a `ValueError`.

<br />

<br />

<br />

| ## Args ||
|---|---|
| `value` | A Python scalar, list or tuple of values, or a N-dimensional numpy array. All elements of the initialized variable will be set to the corresponding value in the `value` argument. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. |
| `verify_shape` | Boolean that enables verification of the shape of `value`. If `True`, the initializer will throw an error if the shape of `value` is not compatible with the shape of the initialized tensor. |

<br />

<br />

<br />

<br />

| ## Raises ||
|---|---|
| `TypeError` | If the input `value` is not one of the expected types. |

<br />

<br />

<br />

<br />

| ## Examples ||
|---|---|
| The following example can be rewritten using a numpy.ndarray instead of the `value` list, even reshaped, as shown in the two commented lines below the `value` list initialization. ||

<br />

    value = [0, 1, 2, 3, 4, 5, 6, 7]
    init = tf.compat.v1.constant_initializer(value)
    # fitting shape
    with tf.compat.v1.Session():
      x = tf.compat.v1.get_variable('x', shape=[2, 4], initializer=init)
      x.initializer.run()
      print(x.eval())
    [[0. 1. 2. 3.]
     [4. 5. 6. 7.]]
    # Larger shape
    with tf.compat.v1.Session():
      y = tf.compat.v1.get_variable('y', shape=[3, 4], initializer=init)
      y.initializer.run()
      print(y.eval())
    [[0.  1.  2.  3.]
     [4.  5.  6.  7.]
     [7.  7.  7.  7.]]
    # Smaller shape
    with tf.compat.v1.Session():
      z = tf.compat.v1.get_variable('z', shape=[2, 3], initializer=init)
    Traceback (most recent call last):

    ValueError: Too many elements provided. Needed at most 6, but received 8
    # Shape verification
    init_verify = tf.compat.v1.constant_initializer(value, verify_shape=True)
    with tf.compat.v1.Session():
     u = tf.compat.v1.get_variable('u', shape=[3, 4],
                                   initializer=init_verify)
    Traceback (most recent call last):

    TypeError: Expected Tensor's shape: (3, 4), got (8,).

## Methods

### `from_config`

[View source](https://github.com/tensorflow/tensorflow/blob/v2.21.0/tensorflow/python/ops/init_ops.py#L75-L94)

    @classmethod
    from_config(
        config
    )

Instantiates an initializer from a configuration dictionary.

#### Example:

    initializer = RandomUniform(-1, 1)
    config = initializer.get_config()
    initializer = RandomUniform.from_config(config)

<br />

<br />

<br />

| Args ||
|---|---|
| `config` | A Python dictionary. It will typically be the output of `get_config`. |

<br />

<br />

<br />

<br />

| Returns ||
|---|---|
| An Initializer instance. ||

<br />

### `get_config`

[View source](https://github.com/tensorflow/tensorflow/blob/v2.21.0/tensorflow/python/ops/init_ops.py#L389-L394)

    get_config()

Returns the configuration of the initializer as a JSON-serializable dict.

<br />

<br />

<br />

| Returns ||
|---|---|
| A JSON-serializable Python dict. ||

<br />

### `__call__`

[View source](https://github.com/tensorflow/tensorflow/blob/v2.21.0/tensorflow/python/ops/init_ops.py#L381-L387)

    __call__(
        shape, dtype=None, partition_info=None, verify_shape=None
    )

Returns a tensor object initialized as specified by the initializer.

<br />

<br />

<br />

| Args ||
|---|---|
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |

<br />