Rate this Page

torch.as_tensor#

torch.as_tensor(data:Any,dtype:Optional[dtype]=None,device:Optional[DeviceLikeType])Tensor#

Convertsdata into a tensor, sharing data and preserving autogradhistory if possible.

Ifdata is already a tensor with the requested dtype and devicethendata itself is returned, but ifdata is atensor with a different dtype or device then it’s copied as if usingdata.to(dtype=dtype, device=device).

Ifdata is a NumPy array (an ndarray) with the same dtype and device then atensor is constructed usingtorch.from_numpy().

Ifdata is a CuPy array, the returned tensor will be located on the same device as the CuPy array unlessspecifically overwritten bydevice or a default device. The device of the CuPy array is inferred from thepointer of the array usingcudaPointerGetAttributes unlessdevice is provided with an explicit device index.

See also

torch.tensor() never shares its data and creates a new “leaf tensor” (seeAutograd mechanics).

Parameters
  • data (array_like) – Initial data for the tensor. Can be a list, tuple,NumPyndarray, scalar, and other types.

  • dtype (torch.dtype, optional) – the desired data type of returned tensor.Default: ifNone, infers data type fromdata.

  • device (torch.device, optional) – the device of the constructed tensor. If None and data is a tensorthen the device of data is used. If None and data is not a tensor thenthe result tensor is constructed on the current device.

Example:

>>>a=numpy.array([1,2,3])>>>t=torch.as_tensor(a)>>>ttensor([ 1,  2,  3])>>>t[0]=-1>>>aarray([-1,  2,  3])>>>a=numpy.array([1,2,3])>>>t=torch.as_tensor(a,device=torch.device('cuda'))>>>ttensor([ 1,  2,  3])>>>t[0]=-1>>>aarray([1,  2,  3])