简体   繁体   English

Python:当我使用“ from scipy.sparse import *”时,“ kron”会创建稀疏矩阵吗?

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

For the code below, Mat is a array-type matrix, 对于下面的代码,Mat是一个数组类型的矩阵,

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. 如果我不导入scipy.sparse包,则a数组类型的矩阵 ,也可以执行b If I use 'from scipy.sparse import *', a is a sparse-type matrix , b cannot be exectued. 如果我使用'from scipy.sparse import *',则a稀疏类型矩阵 ,则b 不能执行。 Can someone tell me why kron gives different results? 有人可以告诉我为什么kron给出不同的结果吗? And, whether flatten() can be applied to sparse-type matrix? 而且,flatten()是否可以应用于稀疏类型矩阵?

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 from module import *在应用程序代码中通常被认为是错误的形式,原因是您看到的原因-很难分辨出哪个模块功能来自何处,特别是如果您对多个模块执行此操作时

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. 取消对第二行可能会影响地方ones ,并kron从何而来。 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. 然后你就可以换npsparse要使用稀疏的版本,读者会立刻知道你正在使用哪一个。 And you'll get an error if you try to use a sparse version when in fact there isn't one. 如果您尝试使用稀疏版本,而实际上却没有一个稀疏版本,则会收到错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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