zoukankan      html  css  js  c++  java
  • scipy读取稀疏数据

    转自:https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.coo_matrix.tocsr.html

    https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.mmread.html

    1.基本用法

    >>> from numpy import array
    >>> from scipy.sparse import coo_matrix
    >>> row  = array([0,0,1,3,1,0,0])
    >>> col  = array([0,2,1,3,1,0,0])
    >>> data = array([1,1,1,1,1,1,1])
    >>> A = coo_matrix( (data,(row,col)), shape=(4,4)).tocsr()
    >>> A.todense()
    matrix([[3, 0, 1, 0],
            [0, 2, 0, 0],
            [0, 0, 0, 0],
            [0, 0, 0, 1]])

    直接根据行index,列index,以及data建立索引,A就是稀疏数据的类型:

    <4x4 sparse matrix of type '<class 'numpy.float32'>'
        with 3 stored elements in Compressed Sparse Row format>

    压缩稀疏行格式。

    2.从文件中读取mtx格式数据并存储为稀疏格式

    count内容:

    %%MatrixMarket matrix coordinate integer general
    4 4 4
    1 1 1
    1 2 1
    1 1 1
    2 3 1

    这里针对第一行,应该是mtx文件的必要格式,需要5列内容。第二行表示的意思分别是:cols,rows,total_nums。

    注意行号和列号都不是从0开始,而是从1,这和计算机中的习惯并不一样,大概是为了更多领域来用这个包吧。

    from numpy import array
    from scipy.io import mmread
    count = mmread('a.mtx').T.tocsr().astype('float32')
    
    #输出:
    >>> count
    <4x4 sparse matrix of type '<class 'numpy.float32'>'
        with 3 stored elements in Compressed Sparse Row format>
    >>> count.todense()
    matrix([[2., 0., 0., 0.],
            [1., 0., 0., 0.],
            [0., 1., 0., 0.],
            [0., 0., 0., 0.]], dtype=float32)

    3.对稀疏矩阵取log 

    from numpy import array
    import numpy as np
    from scipy.sparse import coo_matrix,csr_matrix
    row  = array([0,0,1,3,1,0,0])
    col  = array([0,2,1,3,1,0,0])
    data = array([1,1,1,1,1,1,1])
    A = coo_matrix( (data,(row,col)), shape=(4,4)).tocsr()
    print(A.todense())
    #A=np.log(1+A)#这样会报错
    #NotImplementedError: adding a nonzero scalar to a sparse matrix is not supported
    A=csr_matrix(np.log(A.toarray() + 1))
    print(A.todense())

    不能直接取log,会报错。

    需要转换为array后操作,再转换为array。

    4.对稀疏矩阵的转置

    接上面的代码,可以直接使用

    A=np.transpose(A)
    
    #输出:
    [[3 0 1 0]
     [0 2 0 0]
     [0 0 0 0]
     [0 0 0 1]]
    
    [[3 0 0 0]
     [0 2 0 0]
     [1 0 0 0]
     [0 0 0 1]]

    不需要转换为array就能用np的转置函数。

  • 相关阅读:
    eureka 源码
    注册中心eureka
    自己的spring boot starter
    spring boot基本认识
    我以为我对Kafka很了解,直到我看了此文章
    Spring 中的 18 个注解,你会几个?
    定时任务之crontab命令
    Spring中@Autowired、@Resource和@Inject注解的使用和区别
    Lombok介绍、使用方法和总结
    Mybatis JdbcType与Oracle、MySql数据类型对
  • 原文地址:https://www.cnblogs.com/BlueBlueSea/p/12420773.html
Copyright © 2011-2022 走看看