如何将 numpy.matrix 或数组转换为 scipy 稀疏矩阵 [英] How to transform numpy.matrix or array to scipy sparse matrix

查看:60
本文介绍了如何将 numpy.matrix 或数组转换为 scipy 稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 SciPy 稀疏矩阵,可以使用 todense()toarray() 转换为 NumPy 矩阵或数组.做逆运算的函数有哪些?

我进行了搜索,但不知道哪些关键字应该是正确的搜索词.

解决方案

您可以在初始化稀疏矩阵时将 numpy 数组或矩阵作为参数传递.例如,对于 CSR 矩阵,您可以执行以下操作.

<预><代码>>>>将 numpy 导入为 np>>>从 scipy 导入稀疏>>>A = np.array([[1,2,0],[0,0,3],[1,0,4]])>>>B = np.matrix([[1,2,0],[0,0,3],[1,0,4]])>>>一个数组([[1, 2, 0],[0, 0, 3],[1, 0, 4]])>>>sA = sparse.csr_matrix(A) # 这里是稀疏矩阵的初始化.>>>sB = sparse.csr_matrix(B)>>>萨<3x3 稀疏矩阵的类型 '<type 'numpy.int32'>'具有压缩稀疏行格式的 5 个存储元素>>>>打印 sA(0, 0) 1(0, 1) 2(1, 2) 3(2, 0) 1(2, 2) 4

For SciPy sparse matrix, one can use todense() or toarray() to transform to NumPy matrix or array. What are the functions to do the inverse?

I searched, but got no idea what keywords should be the right hit.

解决方案

You can pass a numpy array or matrix as an argument when initializing a sparse matrix. For a CSR matrix, for example, you can do the following.

>>> import numpy as np
>>> from scipy import sparse
>>> A = np.array([[1,2,0],[0,0,3],[1,0,4]])
>>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]])

>>> A
array([[1, 2, 0],
       [0, 0, 3],
       [1, 0, 4]])

>>> sA = sparse.csr_matrix(A)   # Here's the initialization of the sparse matrix.
>>> sB = sparse.csr_matrix(B)

>>> sA
<3x3 sparse matrix of type '<type 'numpy.int32'>'
        with 5 stored elements in Compressed Sparse Row format>

>>> print sA
  (0, 0)        1
  (0, 1)        2
  (1, 2)        3
  (2, 0)        1
  (2, 2)        4

这篇关于如何将 numpy.matrix 或数组转换为 scipy 稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆