代码之家  ›  专栏  ›  技术社区  ›  uhoh Jacob

numpy.zeros ou like()中subok选项的用途和效用是什么?

  •  1
  • uhoh Jacob  · 技术社区  · 6 年前

    使用numpy's zeros_like 以及相关功能,有一个选项

    苏博克: 布尔,可选。

    numpy.zeros类似(a,dtype=none,order='k',subok=true

    如果为true,则新创建的数组将使用的子类类型为,否则它将是基类数组。默认为true。

    我以为所有的numpy数组都是类 ndarray 我从来没有必要详细研究阵列 子类 . 在什么情况下,我可以选择不使用相同的子类,指定基类的使用?

    1 回复  |  直到 6 年前
        1
  •  2
  •   user3666197    6 年前

    什么 目的 效用 …?

    目的:

    呼叫签名 帮助 或者传递已处理的实例类型,如下所示:

    >>> np.array( np.mat( '1 2; 3 4' ),    # array-to-"process"
                  subok = True             # FLAG True to ["pass-through"] the type
                  )
    matrix([[1, 2],
            [3, 4]])                       # RESULT is indeed the instance of matrix
    

    相反,如果不愿意“再加工”两者 .shape 并使用 subok = False ,生产的 *_alike() 将不会得到相同的类,如“示例”中给出的进程 -生成的输出:

    type(                np.mat( '1 2;3 4' ) )   # <class 'numpy.matrixlib.defmatrix.matrix'>
    type( np.array(      np.mat( '1 2;3 4' ) ) ) # <type 'numpy.ndarray'>
    type( np.zeros_like( np.mat( '1 2;3 4' ) ) ) # <class 'numpy.matrixlib.defmatrix.matrix'>
    
    >>> np.zeros_like(   np.mat( '1 2;3 4' ), subok = True  )
    matrix([[0, 0],
            [0, 0]])
    >>> np.zeros_like(   np.mat( '1 2;3 4' ), subok = False )
    array([[0, 0],
           [0, 0]])
    

    实用程序:

    这些 subok -旗子在更多地方很常见 numpy 功能(不仅仅是 *_like() -S,也在 np.array( ... ) ,因为它对智能类型修改代码设计非常有用,在这种情况下,“生成”过程知道所需的产品类型,因此,如果需要事后修改,则可以在没有不当的类相关开销的情况下实现结果。