Search code examples
python-3.xnumpyscipyscikit-learnsparse-matrix

Logical not on a scipy sparse matrix


I have a bag-of-words representation of a corpus stored in an D by W sparse matrix word_freqs. Each row is a document and each column is a word. A given element word_freqs[d,w] represents the number of occurrences of word w in document d.

I'm trying to obtain another D by W matrix not_word_occs where, for each element of word_freqs:

  • If word_freqs[d,w] is zero, not_word_occs[d,w] should be one.
  • Otherwise, not_word_occs[d,w] should be zero.

Eventually, this matrix will need to be multiplied with other matrices which might be dense or sparse.


I've tried a number of methods, including:

not_word_occs = (word_freqs == 0).astype(int)

This words for toy examples, but results in a MemoryError for my actual data (which is approx. 18,000x16,000).

I've also tried np.logical_not():

word_occs = sklearn.preprocessing.binarize(word_freqs)
not_word_occs = np.logical_not(word_freqs).astype(int)

This seemed promising, but np.logical_not() does not work on sparse matrices, giving the following error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

Any ideas or guidance would be appreciated.

(By the way, word_freqs is generated by sklearn's preprocessing.CountVectorizer(). If there's a solution that involves converting this to another kind of matrix, I'm certainly open to that.)


Solution

  • The complement of the nonzero positions of a sparse matrix is dense. So if you want to achieve your stated goals with standard numpy arrays you will require quite a bit of RAM. Here's a quick and totally unscientific hack to give you an idea, how many arrays of that sort your computer can handle:

    >>> import numpy as np
    >>> a = []
    >>> for j in range(100):
    ...     print(j)
    ...     a.append(np.ones((16000, 18000), dtype=int))
    

    My laptop chokes at j=1. So unless you have a really good computer even if you can get the complement (you can do

    >>> compl = np.ones(S.shape,int)
    >>> compl[S.nonzero()] = 0
    

    ) memory will be an issue.

    One way out may be to not explicitly compute the complement let's call it C = B1 - A, where B1 is the same-shape matrix completely filled with ones and A the adjacency matrix of your original sparse matrix. For example the matrix product XC can be written as XB1 - XA so you have one multiplication with the sparse A and one with B1 which is actually cheap because it boils down to computing row sums. The point here is that you can compute that without computing C first.

    A particularly simple example would be multiplication with a one-hot vector. Such a multiplication just selects a column (if multiplying from the right) or row (if multiplying from the left) of the other matrix. Meaning you just need to find that column or row of the sparse matrix and take the complement (for a single slice no problem) and if you do this for a one-hot matrix, as above you needn't compute the complement explicitly.