B.Du B.Du - 2 months ago 11
Python Question

Python: Does 'kron' create sparse matrix when I use ' from scipy.sparse import * '?

For the code below, Mat is a array-type matrix,

a = kron(Mat,ones((8,1)))
b = a.flatten()


If I don't import scipy.sparse package,
a
is an array-type matrix,
b
can also be executed.
If I use 'from scipy.sparse import *',
a
is a sparse-type matrix,
b
cannot be exectued.
Can someone tell me why
kron
gives different results?
And, whether flatten() can be applied to sparse-type matrix?

Answer

from module import * is generally considered bad form in application code, for the reason you're seeing - it makes it very hard to tell which modules functions are coming from, especially if you do this for more than one module

Right now, you have:

from numpy import *
# from scipy.sparse import *
a = kron(Mat,ones((8,1)))
b = temp.flatten()

Uncommenting the second line might affect where ones and kron comes from. But unless you look up whether sparse redefines these, you won't know. Better to write it like this:

import numpy as np
from scipy import sparse
a = np.kron(Mat, np.ones((8,1)))
b = temp.flatten()

And then you can swap np for sparse where you want to use the sparse version, and the reader will immediately know which one you're using. And you'll get an error if you try to use a sparse version when in fact there isn't one.