torch.dtype 是tensor的类型像 int ,float 等;
torch.device表示了torch.tensor对象在创建之后所存储在的设备名称,像CPU,GPU等
例如:
torch.tensor([1,2,3], dtype=torch.float32, device=torch.device(‘cpu’))
torch.layout表示torch.tensor内存布局的对象
import torch
dev = torch.device('cpu')
a = torch.tensor([2, 2], device=dev)
print(a)
# 这个要看你电脑上的配置了
# dev = torch.device('cuda')
# a = torch.tensor([2, 2], device=dev)
# print(a)
# 非零元素坐标 即(0,0),(1,1),(2,2)为非零元素
i = torch.tensor([[0, 1, 2], [0, 1, 2]])
# 非零元素具体的值
v = torch.tensor([1, 2, 3])
# 将稀疏张量转成稠密张量 (5, 5)张量的形状
b = torch.sparse_coo_tensor(i, v, (5, 5)).to_dense()
print(b)
# 也可以添加参数指定类型和设备
b = torch.sparse_coo_tensor(i, v, (5, 5),
dtype=torch.float32,
device=dev
).to_dense()
print(b)
执行结果
tensor([2, 2])
tensor([[1, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
tensor([[1., 0., 0., 0., 0.],
[0., 2., 0., 0., 0.],
[0., 0., 3., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])