Ad

How To Sparsify A Matrix/array In Python

- 1 answer

I have a simple "matrix" in python that I would like to sparsify:

np.array([[5.72756493, 0.        , 0.        ],
          [2.86378246, 4.96021673, 0.        ],
          [5.72756493, 3.30681115, 2.33826859]])

I would like to reduce it to the following form:

np.array([[5.72756493, 0.        , 0.        ],
          [2.86378246, 4.96021673, 0.        ],
          [0.,         3.30681115, 2.33826859]])

I'm certain there must be some simple function in numpy/scipy that can handle this. I will only be working with small 3x3 matrices, so it needn't be the most optimized method

I want something like: enter image description here

Ad

Answer

A quick web search shows that sparsification is an active computer science research area. Apparently the idea is to make a matrix computationally more efficient by increasing the proportion of zeros. This is done by zeroing out some some low magnitude terms, and doing some sort of sampling of the other terms. But the matrix has to be 'computationally equivalent'.

There's nothing like this in numpy. scipy has a sparse matrix package. It can make a sparse matrix from a 2d numpy array, regardless of how many 0s it has. But there's no sparsifying function. In my experience scipy.sparse matrices are computationally efficient only if the sparsity is on the order of 10% or less (90% zeros).

Someone may have written sparsification code in Python, but it isn't part of these standard packages.

I'll vote for closing.

Ad
source: stackoverflow.com
Ad