简体   繁体   中英

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?

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 = a.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 = a.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM