Nic*_*aiF 4 python numpy scipy sparse-matrix pytorch
我有一个coo_matrix:
from scipy.sparse import coo_matrix
coo = coo_matrix((3, 4), dtype = "int8")
Run Code Online (Sandbox Code Playgroud)
我想要转换为pytorch稀疏张量.根据文档https://pytorch.org/docs/master/sparse.html它应该遵循coo格式,但我找不到一种简单的方法来进行转换.任何帮助将不胜感激!
小智 7
使用Pytorch文档中的数据,只需使用Numpy的属性就可以完成coo_matrix:
import torch
import numpy as np
from scipy.sparse import coo_matrix
coo = coo_matrix(([3,4,5], ([0,1,1], [2,0,2])), shape=(2,3))
values = coo.data
indices = np.vstack((coo.row, coo.col))
i = torch.LongTensor(indices)
v = torch.FloatTensor(values)
shape = coo.shape
torch.sparse.FloatTensor(i, v, torch.Size(shape)).to_dense()
Run Code Online (Sandbox Code Playgroud)
产量
0 0 3
4 0 5
[torch.FloatTensor of size 2x3]
Run Code Online (Sandbox Code Playgroud)