sparse 3d matrix/array in Python?

后端 未结 6 1908
借酒劲吻你
借酒劲吻你 2020-12-02 15:13

In scipy, we can construct a sparse matrix using scipy.sparse.lil_matrix() etc. But the matrix is in 2d.

I am wondering if there is an existing data structure for sp

6条回答
  •  [愿得一人]
    2020-12-02 15:38

    An alternative answer as of 2017 is the sparse package. According to the package itself it implements sparse multidimensional arrays on top of NumPy and scipy.sparse by generalizing the scipy.sparse.coo_matrix layout.

    Here's an example taken from the docs:

    import numpy as np
    n = 1000
    ndims = 4
    nnz = 1000000
    coords = np.random.randint(0, n - 1, size=(ndims, nnz))
    data = np.random.random(nnz)
    
    import sparse
    x = sparse.COO(coords, data, shape=((n,) * ndims))
    x
    # 
    
    x.nbytes
    # 16000000
    
    y = sparse.tensordot(x, x, axes=((3, 0), (1, 2)))
    
    y
    # 
    

提交回复
热议问题