torch.tensor()

方法: 

torch.tensor(data*dtype=Nonedevice=Nonerequires_grad=Falsepin_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 from data.

  • 指定新张量的数据类型。如果没有指定,则自动推断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 (booloptional) – If autograd should record operations on the returned tensor. Default: False.

  • 设置为True时,表示张量需要计算梯度,这在训练神经网络时非常有用

  • pin_memory (booloptional) – 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([])
  • 15
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值