to_variable

paddle.fluid.dygraph.base. to_variable ( value, name=None, zero_copy=None, dtype=None ) [source]
Api_attr

imperative

The API will create a Variable object from tuple, list, numpy.ndarray or Variable object.

Parameters
  • value (tuple|list|ndarray|Variable|Tensor) – Initial data. Can be a list, tuple, NumPy ndarray, Variable, Tensor. The shape can be multi-dimensional. The data type is one of numpy.{float16, float32, float64, int16, int32, int64, uint8, uint16, complex64, complex128}.

  • name (str, optional) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to Name .

  • zero_copy (bool, optional) – Whether to share memory with the input numpy array. This parameter only works with CPUPlace and will be set to True when it is None. Default: None. (Note: zero_copy is discarded temporally for some reason.)

  • dtype (str, optional) – The desired data type of returned Variable . Can be ‘bool’ , ‘float16’ , ‘float32’ , ‘float64’ , ‘int8’ , ‘int16’ , ‘int32’ , ‘int64’ , ‘uint8’ . Default: None.

Returns

If value is a tuple/list/numpy.ndarray object,

return Tensor created from the corresponding numpy.ndarray object, which has same data type and shape with value.

Return type

Variable

Examples

import numpy as np
import paddle.fluid as fluid

with fluid.dygraph.guard(fluid.CPUPlace()):
    x = np.ones([2, 2], np.float32)
    y = fluid.dygraph.to_variable(x, zero_copy=False)
    x[0][0] = -1
    y[0][0].numpy()  # array([1.], dtype=float32)
    y = fluid.dygraph.to_variable(x)
    x[0][0] = 0
    y[0][0].numpy()  # array([0.], dtype=float32)
    c = np.array([2+1j, 2])
    z = fluid.dygraph.to_variable(c)
    z.numpy() # array([2.+1.j, 2.+0.j])
    z.dtype # 'complex128'

    y = fluid.dygraph.to_variable([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
    y.shape     # [3L, 2L]

    y = fluid.dygraph.to_variable(((0.1, 1.2), (2.2, 3.1), (4.9, 5.2)), dtype='int32')
    y.shape     # [3L, 2L]