代码之家  ›  专栏  ›  技术社区  ›  pyano

用于导入scipy和sklearn模块的语法

  •  3
  • pyano  · 技术社区  · 7 年前

    我使用(仅标准)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'
    

    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])

    1 回复  |  直到 7 年前
        1
  •  2
  •   tel    7 年前

    “问题”

    scipy 公司规模相当大,成员众多。因此,为了避免运行时出现滞后 import 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 是有效的吗 松软的 首先是子包。