Skip to main content
 首页 » 编程设计

python之导入 scipy 和 sklearn 模块的语法

2024年12月31日10kuangbin

我使用(仅标准)Win10、Anaconda-2018.12、Python-3.7、MKL-2019.1、mkl-service-1.1.2、Jupyter ipython-7.2。 see here e.g. 我想知道为什么以下语法适用于 numpy 模块的 import 语句,但不适用于 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 子包。