在我们对某一功能进行测试或展示时
通常都需要构建一系列tensor
用于小型数据测试
以验证功能的正确性或展示的可行性
因此本文就梳理了pytorch
中构建tensor
的一系列方法
数据转tensor
将存储在别的结构中的数据转为tensor
的格式
tensor
内部拷贝源数据并构建返回相应的tensor
必要参数(Parameters)
data
- 传入的结构类型 -array
、list
、tuple
、scalar
(标量)…
可选参数(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
与