[SciPy-user] Unexpected typecasting when adding sparse.lil_matrix

Nathan Bell wnbell@gmail....
Thu Sep 11 10:49:02 CDT 2008


On Thu, Sep 11, 2008 at 11:03 AM, Tony S Yu <tonyyu@mit.edu> wrote:
> This may be expected behavior, but I found it surprising. Addition (or
> any other simple operation) of two lil sparse matrices returns a csc
> sparse matrix. The scipy website suggests that csc and csr matrices
> are more efficient than lil matrices for multiplication and inversion
> (and I guess for addition too), but this typecasting is still a little
> surprising. I was just curious if this is intentional.
>
> Thanks,
> -Tony
>
> #~~~~~~~~~
>
> In [1]: import scipy.sparse as sparse
>
> In [2]: A = sparse.lil_eye([3, 3])
>
> In [3]: A + A
>
> Out[3]:
> <3x3 sparse matrix of type '<type 'numpy.float64'>'
>        with 3 stored elements (space for 3)
>        in Compressed Sparse Column format>
>

That is the intended result (currently).

The issue here is that only some sparse formats define arithmetic
operations, so those that don't are converted to a type that does.
Even if lil_matrix did define addition itself, it would almost
certainly be slower than conversion to a "native" format (i.e. one
with a lower-level C++ implementation).  Furthermore, guaranteeing
that other operations, such as A.transpose(), return the same type as
A would make csr_matrix.transpose() an O(N) method rather than an O(1)
method.

The current implementation is nice because inexperienced users will
often get better performance in subsequent operations.  OTOH, as your
case illustrates, it can lead to surprises.

You can always do (A + B).tolil() if you want the result in a
particular format though.  I'm not sure if your version of SciPy
supports lil_matrix(A + B), but that works now also.

-- 
Nathan Bell wnbell@gmail.com
http://graphics.cs.uiuc.edu/~wnbell/


More information about the SciPy-user mailing list