python科学计算六:scipy矩阵操作

 七种矩阵类型

  1. csc_matrix: Compressed Sparse Column format
  2. csr_matrix: Compressed Sparse Row format
  3. bsr_matrix: Block Sparse Row format
  4. lil_matrix: List of Lists format
  5. dok_matrix: Dictionary of Keys format
  6. coo_matrix: COOrdinate format (aka IJV, triplet format)
  7. dia_matrix: DIAgonal format

使用lil_matrix和dok_matrix来高效的构建矩阵。lil_matrix支持与numpy类似的基本的切片和索引等操作,coo_matrix也可以用来有效构建矩阵。

为了进行一些操作,比如:乘法、加法、转置等,首先需要将数组转为csc或者csr形式。lil_matrix形式是基于row的,因此能够很高效的转为csr,但是转为csc效率相对较低。

1、 scipy.sparse.coo_matrix (arg1,shape=None,dtype=None,copy=False):
  坐标形式的一种稀疏矩阵。
优点:快速的和CSR/CSC formats转换、允许重复录入
缺点:不能直接进行科学计算和切片操作
   1)、构造过程: coo_matrix(D): with a dense matrix D
                   coo_matrix(S): with another sparse matrix S (equivalent to S.tocoo())
                   coo_matrix((M, N), [dtype]):to construct an empty matrix with shape (M, N) dtype is optional, defaulting to dtype=’d’.
                   coo_matrix((data, (i, j)), [shape=(M, N)]):
                        to construct from three arrays:
  1. data[:] the entries of the matrix, in any order
  2. i[:] the row indices of the matrix entries
  3. j[:] the column indices of the matrix entries

Where A[i[k], j[k]] = data[k]. When shape is not specified, it is inferred from the index arrays

 示例:

>>> from scipy.sparse import coo_matrix
>>> coo_matrix((3,4), dtype=np.int8).todense()
matrix([[0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]], dtype=int8)
>>> row  = np.array([0,3,1,0])
>>> col  = np.array([0,3,1,2])
>>> data = np.array([4,5,7,9])
>>> coo_matrix((data,(row,col)), shape=(4,4)).todense()
matrix([[4, 0, 9, 0],
        [0, 7, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 5]])
>>> # example with duplicates
>>> row  = np.array([0,0,1,3,1,0,0])
>>> col  = np.array([0,2,1,3,1,0,0])
>>> data = np.array([1,1,1,1,1,1,1])
>>> coo_matrix((data, (row,col)), shape=(4,4)).todense()
matrix([[3, 0, 1, 0],
        [0, 2, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 1]])

最常用的函数:

tocsc()Return a copy of this matrix in Compressed Sparse Column format
tocsr()Return a copy of this matrix in Compressed Sparse Row format
todense([order, out])Return a dense matrix representation of this matrix

2、  scipy.sparse.csc_matrix(arg1, shape=None, dtype=None, copy=False)

压缩的列稀疏矩阵

>>> from scipy.sparse import *
>>> from scipy import *
>>> csc_matrix( (3,4), dtype=int8 ).todense()
matrix([[0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]], dtype=int8)
>>> row = array([0,2,2,0,1,2])
>>> col = array([0,0,1,2,2,2])
>>> data = array([1,2,3,4,5,6])
>>> csc_matrix( (data,(row,col)), shape=(3,3) ).todense()
matrix([[1, 0, 4],
        [0, 0, 5],
        [2, 3, 6]])
>>> indptr = array([0,2,3,6])
>>> indices = array([0,2,2,0,1,2])
>>> data = array([1,2,3,4,5,6])
>>> csc_matrix( (data,indices,indptr), shape=(3,3) ).todense()
matrix([[1, 0, 4],
        [0, 0, 5],
        [2, 3, 6]])

3、scipy.sparse.csr_matrix(arg1, shape=None, dtype=None, copy=False)压缩的行稀疏矩阵

方法:1、scipy.sparse.hstack(blocks, format=None, dtype=None)

       Stack sparse matrices horizontally (column wise)

>>> from scipy.sparse import coo_matrix, hstack

>>> A = coo_matrix([[1,2],[3,4]])

>>> B = coo_matrix([[5],[6]])

>>> hstack( [A,B] ).todense()

      matrix([[1, 2, 5],

                 [3, 4, 6]])

           2、scipy.sparse.vstack(blocks, format=None, dtype=None)

               Stack sparse matrices vertically (row wise)

>>> from scipy.sparse import coo_matrix, vstack

>>> A = coo_matrix([[1,2],[3,4]])

>>> B = coo_matrix([[5,6]])

>>> vstack( [A,B] ).todense()

matrix([[1, 2],   

            [3, 4],

            [5, 6]])

补充:

稀疏矩阵-sparse

from scipy import sparse

稀疏矩阵的储存形式

在科学与工程领域中求解线性模型时经常出现许多大型的矩阵,这些矩阵中大部分的元素都为0,被称为稀疏矩阵。用NumPy的ndarray数组保存这样的矩阵,将很浪费内存,由于矩阵的稀疏特性,可以通过只保存非零元素的相关信息,从而节约内存的使用。此外,针对这种特殊结构的矩阵编写运算函数,也可以提高矩阵的运算速度。

scipy.sparse库中提供了多种表示稀疏矩阵的格式,每种格式都有不同的用处,其中dok_matrixlil_matrix适合逐渐添加元素。

dok_matrixdict继承,它采用字典保存矩阵中不为0的元素:字典的键是一个保存元素(行,列)信息的元组,其对应的值为矩阵中位于(行,列)中的元素值。显然字典格式的稀疏矩阵很适合单个元素的添加、删除和存取操作。通常用来逐渐添加非零元素,然后转换成其它支持快速运算的格式。

a = sparse.dok_matrix((10, 5))
a[2:5, 3] = 1.0, 2.0, 3.0
print a.keys()
print a.values()
[(2, 3), (3, 3), (4, 3)]
[1.0, 2.0, 3.0]

lil_matrix使用两个列表保存非零元素。data保存每行中的非零元素,rows保存非零元素所在的列。这种格式也很适合逐个添加元素,并且能快速获取行相关的数据。

b = sparse.lil_matrix((10, 5))
b[2, 3] = 1.0
b[3, 4] = 2.0
b[3, 2] = 3.0
print b.data
print b.rows
[[] [] [1.0] [3.0, 2.0] [] [] [] [] [] []]
[[] [] [3] [2, 4] [] [] [] [] [] []]

coo_matrix采用三个数组rowcoldata保存非零元素的信息。这三个数组的长度相同,row保存元素的行,col保存元素的列,data保存元素的值。coo_matrix不支持元素的存取和增删,一旦创建之后,除了将之转换成其它格式的矩阵,几乎无法对其做任何操作和矩阵运算。

coo_matrix支持重复元素,即同一行列坐标可以出现多次,当转换为其它格式的矩阵时,将对同一行列坐标对应的多个值进行求和。在下面的例子中,(2,3)对应两个值:1和10,将其转换为ndarray数组时这两个值加在一起,所以最终矩阵中(2,3)坐标上的值为11。

许多稀疏矩阵的数据都是采用这种格式保存在文件中的,例如某个CSV文件中可能有这样三列:“用户ID,商品ID,评价值”。采用numpy.loadtxtpandas.read_csv将数据读入之后,可以通过coo_matrix快速将其转换成稀疏矩阵:矩阵的每行对应一位用户,每列对应一件商品,而元素值为用户对商品的评价。

row = [2, 3, 3, 2]
col = [3, 4, 2, 3]
data = [1, 2, 3, 10]
c = sparse.coo_matrix((data, (row, col)), shape=(5, 6))
print c.col, c.row, c.data
print c.toarray()
[3 4 2 3] [2 3 3 2] [ 1  2  3 10]
[[ 0  0  0  0  0  0]
 [ 0  0  0  0  0  0]
 [ 0  0  0 11  0  0]
 [ 0  0  3  0  2  0]
 [ 0  0  0  0  0  0]]

 

 

  • 15
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值