将 scipy coo_matrix 转换为 pytorch 稀疏张量
Converting a scipy coo_matrix to pytorch sparse tensor
我有一个 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 docs中的数据,只需使用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()
我有一个 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 docs中的数据,只需使用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()