![](/img/trans.png)
[英]How to convert a sparse matrix to a dense matrix from .mat file in Python?
[英]How to convert sparse matrix to dense form using python
我有以下我认为稀疏的矩阵。 我尝试使用x.dense格式转换为密集模式,但从未成功。 有关如何执行此操作的任何建议吗?谢谢。
mx=[[(0, 2), (1, 1), (2, 1), (3, 1), (4, 1), (5, 3), (6, 4), (7, 2), (8, 5), (9, 1)],
[(10, 1), (11, 5), (12, 2), (13, 1), (21, 1), (22, 1), (23, 1), (24, 1), (25, 1), (26, 2)],
[(27, 2), (28, 1), (29, 1), (30, 1), (31, 2), (32, 1), (33, 1), (34, 1), (35, 1), (36, 1)]]
有人在下面提出了解决方案,但是有更好的方法吗?
def assign_coo_to_dense(sparse, dense):
dense[sparse.row, sparse.col] = sparse.data
mx.todense()。 预期的输出应以以下形式出现:[[2,1,1,1,1,3,4],[1,5,2,1,1,1,1],[2,1,1,1, 2,1,1,1]]
列表理解是最简单的方法:
new_list = [[b for _,b in sub] for sub in mx]
结果:
>>> new_list
[[2, 1, 1, 1, 1, 3, 4, 2, 5, 1], [1, 5, 2, 1, 1, 1, 1, 1, 1, 2], [2, 1, 1, 1, 2, 1, 1, 1, 1, 1]]
您的源数据实际上与SciPy中稀疏矩阵支持的任何内置格式都不匹配(请参阅http://docs.scipy.org/doc/scipy/reference/sparse.html和http://en.wikipedia。 org / wiki / Sparse_matrix ),因此在这里使用.todense()
并不是很有效。 特别是,如果您有以下内容:
import numpy as np
my_sparseish_matrix = np.array([[(1, 2), (3, 4)]])
那么my_sparseish_matrix
将已经是一个密集的numpy数组! .todense()
在其上调用.todense()
会产生错误,而且还是没有意义的。
因此,我的建议是使用几个for
循环显式构造密集数组。 为此,您需要知道所得向量中可能有多少个项目-称为N
dense_vector = np.zeros((N, ), int)
for inner in mx:
for index, value in inner:
dense_vector[index] = value
这是一种很简单的方法来完成您所要的操作:
dense = [[int(''.join(str(val) for _, val in doc))] for doc in mx]
基本上,它会将嵌套元组中的每个值转换为字符串,并将所有这些字符串连接在一起,然后将其转换回整数。 对mx
每个元素重复上述步骤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.