将scipy coo_matrix转换为pytorch稀疏张量

时间:2018-06-03 09:54:49

标签: python numpy scipy sparse-matrix pytorch

我有一个coo_matrix:

const breakPoint00 = 1250
const breakPoint01 = breakPoint00 + 230
const animation01 = ReactDOM.findDOMNode(this.animation01)

if (scrollY > breakPoint00) {
  animation01.style.transform = `translateY(0px)`
} else (scrollY > breakPoint01) {
  animation01.style.transform = `translateY(200px)`
} 

我想要转换为pytorch稀疏张量。根据文档https://pytorch.org/docs/master/sparse.html,它应该遵循coo格式,但我找不到一种简单的方法来进行转换。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:6)

使用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]

答案 1 :(得分:0)

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()