torch.as_tensor¶
- torch.as_tensor(data: Any, dtype: Optional[dtype] = None, device: Optional[DeviceLikeType]) Tensor ¶
将
data
转换为 tensor,如果可能,共享数据并保留自动求导历史。如果
data
已是具有所需数据类型 (dtype
) 和设备 (device
) 的 tensor,则直接返回data
本身;但如果data
是具有不同数据类型或设备的 tensor,则会像使用 data.to(dtype=dtype, device=device) 一样进行复制。如果
data
是具有相同数据类型 (dtype
) 和设备的 NumPy 数组(ndarray),则使用torch.from_numpy()
构造一个 tensor。如果
data
是 CuPy 数组,则返回的 tensor 将位于与 CuPy 数组相同的设备上,除非被device
或默认设备明确覆盖。另请参阅
torch.tensor()
从不共享其数据,而是创建一个新的“叶子 tensor”(参见自动求导机制)。- 参数
data (array_like) – tensor 的初始数据。可以是 list、tuple、NumPy
ndarray
、标量及其他类型。dtype (
torch.dtype
, 可选) – 返回 tensor 的所需数据类型。默认值:如果为None
,则从data
推断数据类型。device (
torch.device
, 可选) – 构造的 tensor 所在的设备。如果为 None 且 data 是一个 tensor,则使用 data 的设备。如果为 None 且 data 不是一个 tensor,则结果 tensor 将在当前设备上构造。
示例
>>> a = numpy.array([1, 2, 3]) >>> t = torch.as_tensor(a) >>> t tensor([ 1, 2, 3]) >>> t[0] = -1 >>> a array([-1, 2, 3]) >>> a = numpy.array([1, 2, 3]) >>> t = torch.as_tensor(a, device=torch.device('cuda')) >>> t tensor([ 1, 2, 3]) >>> t[0] = -1 >>> a array([1, 2, 3])