In the 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 is equivalent to setting verify_shape to False.
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.
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.
Raises
TypeError
If the input value is not one of the expected types.
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.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-04-26 UTC."],[],[],null,["# tf.compat.v1.constant_initializer\n\n\u003cbr /\u003e\n\n|----------------------------------------------------------------------------------------------------------------------------|\n| [View source on GitHub](https://github.com/tensorflow/tensorflow/blob/v2.16.1/tensorflow/python/ops/init_ops.py#L219-L394) |\n\nInitializer that generates tensors with constant values.\n\n#### View aliases\n\n\n**Compat aliases for migration**\n\nSee\n[Migration guide](https://www.tensorflow.org/guide/migrate) for\nmore details.\n\n[`tf.compat.v1.initializers.constant`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/constant_initializer)\n\n\u003cbr /\u003e\n\n tf.compat.v1.constant_initializer(\n value=0,\n dtype=../../../tf/dtypes#float32,\n verify_shape=False\n )\n\n\u003cbr /\u003e\n\nMigrate to TF2\n--------------\n\n\u003cbr /\u003e\n\n| **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.\n\nAlthough it is a legacy API endpoint, [`tf.compat.v1.constant_initializer`](../../../tf/compat/v1/constant_initializer)\nis compatible with eager execution and [`tf.function`](../../../tf/function).\n\nTo migrate to a non-legacy TF2 API, please use [`tf.constant_initializer`](../../../tf/constant_initializer)\ninstead. The `dtype`\nargument in [`tf.compat.v1.constant`*initializer.* *init*`_()`](../../../tf/compat/v1/constant_initializer#__init__) does not exist in\n[`tf.constant`*initializer.* *init*`_()`](../../../tf/constant_initializer#__init__). However, you can specify the `dtype` in\n`__call__()` in both cases.\n\nIn the [`compat.v1`](../../../tf/compat/v1) symbol, if `verify_shape` is set to `True`, an exception\nis raised when initializing a variable with a different shape from\n`value`. If set to `False`, `value` is reshaped to initialize the variable\nif necessary. An exception would only be raised when the number of\nelements are different.\n\nThe `verify_shape` argument is not supported in TF2. Using\n[`tf.constant_initializer`](../../../tf/constant_initializer) is equivalent to setting `verify_shape` to `False`.\n\n#### Structural Mapping to TF2\n\nBefore: \n\n value = [0, 1, 2, 3, 4, 5, 6, 7]\n initializer = tf.compat.v1.constant_initializer(\n value=value,\n dtype=tf.float32,\n verify_shape=False)\n variable = tf.Variable(initializer(shape=[2, 4]))\n\nAfter: \n\n value = [0, 1, 2, 3, 4, 5, 6, 7]\n initializer = tf.constant_initializer(value=value)\n tf.Variable(initializer(shape=[2, 4], dtype=tf.float32))\n\n#### How to Map Arguments\n\n| TF1 Arg Name | TF2 Arg Name | Note |\n|------------------|---------------|---------------------------------------|\n| `value` | `value` | In constructor |\n| `dtype` | `dtype` | In `__call__()` method |\n| `verify_shape` | Not Supported | Equivalent to set to `False` |\n| `partition_info` | - | (`__call__` arg in TF1) Not supported |\n\n#### Before \\& After Usage Example\n\nBefore: \n\n value = [1., 2., 3., 4.]\n initializer = tf.compat.v1.constant_initializer(\n value=value, dtype=tf.float32, verify_shape=True)\n tf.Variable(initializer(shape=[2, 2])).numpy()\n Traceback (most recent call last):\n\n TypeError: Expected Tensor's shape: (2, 2), got (4,).\n initializer = tf.compat.v1.constant_initializer(\n value=value, dtype=tf.float32, verify_shape=False)\n tf.Variable(initializer(shape=[2, 2])).numpy()\n array([[1., 2.],\n [3., 4.]], dtype=float32)\n\nAfter: \n\n value = [1., 2., 3., 4.]\n initializer = tf.constant_initializer(value=value)\n tf.Variable(initializer(shape=[2, 2], dtype=tf.float32)).numpy()\n array([[1., 2.],\n [3., 4.]], dtype=float32)\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nDescription\n-----------\n\n### Used in the notebooks\n\n| Used in the guide |\n|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| - [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) |\n\nThe resulting tensor is populated with values of type `dtype`, as\nspecified by arguments `value` following the desired `shape` of the\nnew tensor (see examples below).\n\nThe argument `value` can be a constant value, or a list of values of type\n`dtype`. If `value` is a list, then the length of the list must be less\nthan or equal to the number of elements implied by the desired shape of the\ntensor. In the case where the total number of elements in `value` is less\nthan the number of elements required by the tensor shape, the last element\nin `value` will be used to fill the remaining entries. If the total number of\nelements in `value` is greater than the number of elements required by the\ntensor shape, the initializer will raise a `ValueError`.\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Args ---- ||\n|----------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `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. |\n| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. |\n| `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. |\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Raises ------ ||\n|-------------|--------------------------------------------------------|\n| `TypeError` | If the input `value` is not one of the expected types. |\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Examples -------- ||\n|---|---|\n| 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. ||\n\n\u003cbr /\u003e\n\n value = [0, 1, 2, 3, 4, 5, 6, 7]\n init = tf.compat.v1.constant_initializer(value)\n # fitting shape\n with tf.compat.v1.Session():\n x = tf.compat.v1.get_variable('x', shape=[2, 4], initializer=init)\n x.initializer.run()\n print(x.eval())\n [[0. 1. 2. 3.]\n [4. 5. 6. 7.]]\n # Larger shape\n with tf.compat.v1.Session():\n y = tf.compat.v1.get_variable('y', shape=[3, 4], initializer=init)\n y.initializer.run()\n print(y.eval())\n [[0. 1. 2. 3.]\n [4. 5. 6. 7.]\n [7. 7. 7. 7.]]\n # Smaller shape\n with tf.compat.v1.Session():\n z = tf.compat.v1.get_variable('z', shape=[2, 3], initializer=init)\n Traceback (most recent call last):\n\n ValueError: Too many elements provided. Needed at most 6, but received 8\n # Shape verification\n init_verify = tf.compat.v1.constant_initializer(value, verify_shape=True)\n with tf.compat.v1.Session():\n u = tf.compat.v1.get_variable('u', shape=[3, 4],\n initializer=init_verify)\n Traceback (most recent call last):\n\n TypeError: Expected Tensor's shape: (3, 4), got (8,).\n\nMethods\n-------\n\n### `from_config`\n\n[View source](https://github.com/tensorflow/tensorflow/blob/v2.16.1/tensorflow/python/ops/init_ops.py#L75-L94) \n\n @classmethod\n from_config(\n config\n )\n\nInstantiates an initializer from a configuration dictionary.\n\n#### Example:\n\n initializer = RandomUniform(-1, 1)\n config = initializer.get_config()\n initializer = RandomUniform.from_config(config)\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Args ||\n|----------|-----------------------------------------------------------------------|\n| `config` | A Python dictionary. It will typically be the output of `get_config`. |\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Returns ||\n|---|---|\n| An Initializer instance. ||\n\n\u003cbr /\u003e\n\n### `get_config`\n\n[View source](https://github.com/tensorflow/tensorflow/blob/v2.16.1/tensorflow/python/ops/init_ops.py#L389-L394) \n\n get_config()\n\nReturns the configuration of the initializer as a JSON-serializable dict.\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Returns ||\n|---|---|\n| A JSON-serializable Python dict. ||\n\n\u003cbr /\u003e\n\n### `__call__`\n\n[View source](https://github.com/tensorflow/tensorflow/blob/v2.16.1/tensorflow/python/ops/init_ops.py#L381-L387) \n\n __call__(\n shape, dtype=None, partition_info=None, verify_shape=None\n )\n\nReturns a tensor object initialized as specified by the initializer.\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Args ||\n|------------------|--------------------------------------------------------------------------|\n| `shape` | Shape of the tensor. |\n| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |\n| `partition_info` | Optional information about the possible partitioning of a tensor. |\n\n\u003cbr /\u003e"]]