python - 将 scipy coo_matrix 转换为 pytorch 稀疏张量

标签 python numpy scipy sparse-matrix pytorch

我有一个 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]

关于python - 将 scipy coo_matrix 转换为 pytorch 稀疏张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50665141/

相关文章:

python - 类型错误 : unsupported operand type(s) for |: 'tuple' and 'bool'

python - 从 Numpy 向量数组中删除重复项(在给定的公差范围内)

python scipy 统计模块 : ValueError: 'axis' entry is out of bounds

python - 重新分配 numpy.array()

python - 将输出转换为 numpy 数组

python - python中的色差估计

python - Curve_fit 在指数威 bool 分布上失败

python - Python下的XQuery库

python - Django render_to_response 未按预期工作

Python TypeError : expected a character buffer object, 个人理解错误