Instantiates a variable and returns it. Arguments: value: Numpy array, initial value of the tensor. dtype: Tensor type. name: Optional name string for the tensor. constraint: Optional projection function to be applied to the variable after an optimizer update.
(value, dtype=None, name=None, constraint=None)
| 762 | |
| 763 | @keras_export('keras.backend.variable') |
| 764 | def variable(value, dtype=None, name=None, constraint=None): |
| 765 | """Instantiates a variable and returns it. |
| 766 | |
| 767 | Arguments: |
| 768 | value: Numpy array, initial value of the tensor. |
| 769 | dtype: Tensor type. |
| 770 | name: Optional name string for the tensor. |
| 771 | constraint: Optional projection function to be |
| 772 | applied to the variable after an optimizer update. |
| 773 | |
| 774 | Returns: |
| 775 | A variable instance (with Keras metadata included). |
| 776 | |
| 777 | Examples: |
| 778 | ```python |
| 779 | >>> import numpy as np |
| 780 | >>> from keras import backend as K |
| 781 | >>> val = np.array([[1, 2], [3, 4]]) |
| 782 | >>> kvar = K.variable(value=val, dtype='float64', name='example_var') |
| 783 | >>> K.dtype(kvar) |
| 784 | 'float64' |
| 785 | >>> print(kvar) |
| 786 | example_var |
| 787 | >>> kvar.eval() |
| 788 | array([[ 1., 2.], |
| 789 | [ 3., 4.]]) |
| 790 | ``` |
| 791 | """ |
| 792 | if dtype is None: |
| 793 | dtype = floatx() |
| 794 | if hasattr(value, 'tocoo'): |
| 795 | sparse_coo = value.tocoo() |
| 796 | indices = np.concatenate((np.expand_dims(sparse_coo.row, 1), np.expand_dims( |
| 797 | sparse_coo.col, 1)), 1) |
| 798 | v = sparse_tensor.SparseTensor( |
| 799 | indices=indices, values=sparse_coo.data, dense_shape=sparse_coo.shape) |
| 800 | v._keras_shape = sparse_coo.shape |
| 801 | return v |
| 802 | v = variables_module.Variable( |
| 803 | value, |
| 804 | dtype=dtypes_module.as_dtype(dtype), |
| 805 | name=name, |
| 806 | constraint=constraint) |
| 807 | if isinstance(value, np.ndarray): |
| 808 | v._keras_shape = value.shape |
| 809 | elif hasattr(value, 'shape'): |
| 810 | v._keras_shape = int_shape(value) |
| 811 | track_variable(v) |
| 812 | return v |
| 813 | |
| 814 | |
| 815 | def track_tf_optimizer(tf_optimizer): |
no test coverage detected