我有一个coo_matrix:
from scipy.sparse import coo_matrix
coo = coo_matrix((3, 4), dtype = "int8")
我想转换为 pytorch 稀疏张量。根据文档https://pytorch.org/docs/master/sparse.html它应该遵循coo格式,但我找不到简单的方法来进行转换。任何帮助将不胜感激!
使用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()
输出
0 0 3
4 0 5
[torch.FloatTensor of size 2x3]
import torch
import numpy as np
from scipy.sparse import coo_matrix
coo = coo_matrix((3, 4), dtype = "int8")
row = torch.from_numpy(coo.row.astype(np.int64)).to(torch.long)
col = torch.from_numpy(coo.col.astype(np.int64)).to(torch.long)
edge_index = torch.stack([row, col], dim=0)
#Presuming values are floats, can use np.int64 for dtype=int8
val = torch.from_numpy(coo.data.astype(np.float64)).to(torch.float)
out = torch.sparse.FloatTensor(edge_index, val, torch.Size(coo.shape)).to_dense()
如果您想将
scipy.sparse.csr_matrix
转换为 torch.sparse_coo_tensor
,您可以按照以下方式进行:
import torch
from scipy.sparse import csr_matrix
csr = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
# Convert to PyTorch sparse tensor
pt_tensor = torch.sparse_coo_tensor(csr.nonzero(), csr.data, csr.shape)
输出:
tensor(indices=tensor([[0, 0, 1, 2, 2],
[0, 1, 2, 0, 2]]),
values=tensor([1, 2, 3, 4, 5]),
size=(3, 3), nnz=5, layout=torch.sparse_coo)