tensor数据类型转换_Pytorch tensor全面了解 | tensor的构建方法大全

本文详细介绍了如何在PyTorch中构建Tensor,包括从不同数据结构转换到Tensor,创建指定形状的Tensor,以及各种类型的随机数生成。内容涵盖了数据转tensor、sparse_coo_tensor、as_tensor、from_numpy等多个方法,同时讲解了zeros、ones、empty、full等构造函数以及random、normal等随机分布生成函数。
摘要由CSDN通过智能技术生成

18b9fb24c15d400bb4c698466ce5f203.png

在我们对某一功能进行测试或展示时

通常都需要构建一系列tensor用于小型数据测试

以验证功能的正确性或展示的可行性

因此本文就梳理了pytorch中构建tensor的一系列方法


数据转tensor

将存储在别的结构中的数据转为tensor的格式

tensor

内部拷贝源数据并构建返回相应的tensor

必要参数(Parameters)

  • data - 传入的结构类型 - arraylisttuplescalar(标量)…

可选参数(Keywords)

  • dtype - 生成的数据类型 - torch.float.double.int.long
  • requires_grad - 是否需要计算梯度
  • device - 表示tensor所在的设备 - torhc.device('cpu').device('cuda')

Test

a = torch.tensor(1.0)
b = torch.tensor([1, 2, 3], dtype=torch.float64, device=torch.device('cuda:0'))
c = torch.tensor(1.66666666666, dtype=torch.float)
d = torch.tensor(1.66666666666, dtype=torch.double)
e = torch.tensor([])

Output

a = tensor(1.)
b = tensor([1., 2., 3.], device='cuda:0', dtype=torch.float64)
c = tensor(1.6667)
d = tensor(1.6667, dtype=torch.float64)
e = tensor([])

sparse_coo_tensor

将数据转化为稀疏张量

Parameters:

  • indices - N个非零值的索引 - shape(2, N)
  • values - 值 - 索引对应的N个值
  • size - 稀疏tensor的形状 - 默认为符合输入要求的最小形状

Keywords : dtype - device - requires_grad

Test 1

i = torch.tensor([[0, 1, 1], [2, 0, 2]])
v = torch.tensor([3, 4, 5], dtype=torch.float32)
torch.sparse_coo_tensor(i, v)

Output 1

tensor(indices=tensor([[0, 1, 1],
                       [2, 0, 2]]),
       values=tensor([3., 4., 5.]),
       size=(2, 3), nnz=3, dtype=torch.float32, layout=torch.sparse_coo)
# nnz: number of nonzero - 存储非零值的数目
# layout: 表示在内存中的布局形式 - 先放一放

Test 2 尝试手动指定size

i = torch.tensor([[0, 1, 1],
                  [2, 0, 2]])
v = torch.tensor([3, 4, 5],dtype=torch.float32)
torch.sparse_coo_tensor(i, v, [2, 4])

Output 2

tensor(indices=tensor([[0, 1, 1],
                       [2, 0, 2]]),
       values=tensor([3., 4., 5.]),
       size=(2, 4), nnz=3, dtype=torch.float32, layout=torch.sparse_coo)

as_tensor

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值