to_tensor¶
- paddle. to_tensor ( data, dtype=None, place=None, stop_gradient=True ) [source]
-
Constructs a
paddle.Tensorfromdata, which can be scalar, tuple, list, numpy.ndarray, paddle.Tensor.If the
datais already a Tensor, copy will be performed and return a new tensor. If you only want to change stop_gradient property, please callTensor.stop_gradient = stop_gradientdirectly.- Parameters
-
data (scalar|tuple|list|ndarray|Tensor) – Initial data for the tensor. Can be a scalar, list, tuple, numpy.ndarray, paddle.Tensor.
dtype (str|np.dtype, optional) – The desired data type of returned tensor. Can be ‘bool’ , ‘float16’ , ‘float32’ , ‘float64’ , ‘int8’ , ‘int16’ , ‘int32’ , ‘int64’ , ‘uint8’, ‘complex64’ , ‘complex128’. Default: None, infers dtype from
dataexcept for python float number which gets dtype fromget_default_type.place (CPUPlace|CUDAPinnedPlace|CUDAPlace|str, optional) – The place to allocate Tensor. Can be CPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If
placeis string, It can becpu,gpu:xandgpu_pinned, wherexis the index of the GPUs.stop_gradient (bool, optional) – Whether to block the gradient propagation of Autograd. Default: True.
- Returns
-
A Tensor constructed from
data. - Return type
-
Tensor
- Raises
-
TypeError – If the data type of
datais not scalar, list, tuple, numpy.ndarray, paddle.TensorValueError – If
datais tuple|list, it can’t contain nested tuple|list with different lengths , such as: [[1, 2], [3, 4, 5]]TypeError – If
dtypeis not bool, float16, float32, float64, int8, int16, int32, int64, uint8, complex64, complex128ValueError – If
placeis not paddle.CPUPlace, paddle.CUDAPinnedPlace, paddle.CUDAPlace or specified pattern string.
Examples:
import paddle type(paddle.to_tensor(1)) # <class 'paddle.Tensor'> paddle.to_tensor(1) # Tensor(shape=[1], dtype=int64, place=CPUPlace, stop_gradient=True, # [1]) x = paddle.to_tensor(1, stop_gradient=False) print(x) # Tensor(shape=[1], dtype=int64, place=CPUPlace, stop_gradient=False, # [1]) paddle.to_tensor(x) # A new tensor will be created with default stop_gradient=True # Tensor(shape=[1], dtype=int64, place=CPUPlace, stop_gradient=True, # [1]) paddle.to_tensor([[0.1, 0.2], [0.3, 0.4]], place=paddle.CPUPlace(), stop_gradient=False) # Tensor(shape=[2, 2], dtype=float32, place=CPUPlace, stop_gradient=False, # [[0.10000000, 0.20000000], # [0.30000001, 0.40000001]]) type(paddle.to_tensor([[1+1j, 2], [3+2j, 4]], dtype='complex64')) # <class 'paddle.Tensor'> paddle.to_tensor([[1+1j, 2], [3+2j, 4]], dtype='complex64') # Tensor(shape=[2, 2], dtype=complex64, place=CPUPlace, stop_gradient=True, # [[(1+1j), (2+0j)], # [(3+2j), (4+0j)]])
