我使用(仅是标准)Win10,Anaconda-2018.12,Python-3.7,MKL-2019.1,mkl-service-1.1.2,Jupyter ipython-7.2。 see here e.g.
我想知道为什么以下语法对带有import
模块的numpy
语句有效,但不适用于scipy
或sklearn
模块:
import scipy as sp
import numpy as np
A = np.random.random_sample((3, 3)) + np.identity(3)
b = np.random.rand((3))
x = sp.sparse.linalg.bicgstab(A,b)
> AttributeError Traceback (most recent call
> last) <ipython-input-1-35204bb7c2bd> in <module>()
> 3 A = np.random.random_sample((3, 3)) + np.identity(3)
> 4 b = np.random.rand((3))
> ----> 5 x = sp.sparse.linalg.bicgstab(A,b)
> AttributeError: module 'scipy' has no attribute 'sparse'
或搭配sklearn
import sklearn as sk
iris = sk.datasets.load_iris()
> AttributeError Traceback (most recent call
> last) <ipython-input-2-f62557c44a49> in <module>()
> 2 import sklearn as sk
> ----> 3 iris = sk.datasets.load_iris() AttributeError: module 'sklearn' has no attribute 'datasets
但是,此语法确实有效(但对于并非真正精益的稀有命令):
import sklearn.datasets as datasets
iris = datasets.load_iris()
和
from scipy.sparse.linalg import bicgstab as bicgstab
x = bicgstab(A,b)
x[0]
array([ 0.44420803, -0.0877137 , 0.54352507])
那是什么类型的问题?可以通过合理的努力消除它吗?
最佳答案
问题”
您遇到的行为实际上是Scipy的功能,尽管乍看起来似乎是个错误。 scipy
的某些子包很大,并且有很多成员。因此,为了避免在运行import scipy
时出现滞后(以及节省系统内存的使用),对scipy
进行了结构化,因此不会自动导入大多数子包。您可以在the docs right here中阅读所有内容。
解决方法
您可以通过稍微使用标准的Python import
语法/语义来解决明显的问题:
import numpy as np
A = np.random.random_sample((3, 3)) + np.identity(3)
b = np.random.rand((3))
import scipy as sp
# this won't work, raises AttributeError
# x = sp.sparse.linalg.bicgstab(A,b)
import scipy.sparse.linalg
# now that same line will work
x = sp.sparse.linalg.bicgstab(A,b)
print(x)
# output: (array([ 0.28173264, 0.13826848, -0.13044883]), 0)
基本上,如果对
sp.pkg_x.func_y
的调用引发了AttributeError
,则可以通过在其前面添加一行来解决该问题,例如:import scipy.pkg_x
当然,这假定
scipy.pkg_x
是有效的scipy
子包。关于python - 导入scipy和sklearn模块的语法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54158139/