方法:
torch.tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False)
作用:
创建tensor类型, 或者将数组转换成tensor类型
Parameters: 参数必选
data (array_like) – Initial data for the tensor. Can be a list, tuple, NumPy ndarray
, scalar, and other types.
要转换的数据。这是一个必须参数,可以是列表、元组、NumPy ndarray、标量或其他支持的数据类型
Keyword Arguments: 可选参数
-
dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if
None
, infers data type fromdata
. -
指定新张量的数据类型。如果没有指定,则自动推断
data
的数据类型 -
device (torch.device, optional) – the device of the constructed tensor. If None and data is a tensor then the device of data is used. If None and data is not a tensor then the result tensor is constructed on the current device.
-
指定张量存储的设备,例如CPU或CUDA(GPU)
-
requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default:
False
. -
设置为
True
时,表示张量需要计算梯度,这在训练神经网络时非常有用 -
pin_memory (bool, optional) – If set, returned tensor would be allocated in the pinned memory. Works only for CPU tensors. Default:
False
. -
仅适用于CPU, 默认为False, 如果设置为True, 则返回的张量在固定内存中分配
官方说明:
来自翻译软件:
讲述了关于如何创建一个不具有自动梯度历史(autograd history)的张量(也被称为“叶子张量”)。主要内容包括:
- 使用`.detach()`或者`torch.tensor(data)`来构建一个新的tensor,但注意使用`torch.tensor(data)`时会复制数据。
- 如果需要保留计算图并且避免数据复制,应该使用`clone()`方法后接`.detach()`操作。
- 为了仅改变`.requires_grad`属性而不改变其他状态,可以使用`t.clone().detach().requires_grad_(True)`表达式。
此外,在"SEE ALSO"部分提到了两个相关函数:
- `as_tensor()`用于在可行时保畋autograd历史并尽可能避免复制数据。
- `from_numpy()`则用于创建和NumPy数组共享内存的张量。
官方示例:
>>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]]) tensor([[ 0.1000, 1.2000], [ 2.2000, 3.1000], [ 4.9000, 5.2000]]) >>> torch.tensor([0, 1]) # Type inference on data tensor([ 0, 1]) >>> torch.tensor([[0.11111, 0.222222, 0.3333333]], ... dtype=torch.float64, ... device=torch.device('cuda:0')) # creates a double tensor on a CUDA device tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device='cuda:0') >>> torch.tensor(3.14159) # Create a zero-dimensional (scalar) tensor tensor(3.1416) >>> torch.tensor([]) # Create an empty tensor (of size (0,)) tensor([])