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

gijlo24d  于 2023-06-29  发布在  其他
关注(0)|答案(1)|浏览(116)

使用numpy的zeros_like和相关函数,可以选择

**subok:**bool,可选。

numpy.zeros_like(a, dtype=None, order='K', subok=True)
如果为True,则新创建的数组将使用'a'的子类类型,否则它将是基类数组。默认为True。
我假设所有的numpy数组都是ndarray类,我从来没有需要详细查看数组的 * 子类 *。在什么情况下我可能不想使用相同的子类,指定基类的使用?

0x6upsns

0x6upsns1#

  • 目的效用**是什么...?*

用途:

call-signature帮助传递处理过的instance-type,如下所示:

>>> 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()将不会得到相同的类,作为“示例”,该过程被给出了使*_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( ... )中),出于同样的目的,因为它对于智能类型修改代码设计非常有用,其中期望的产品类型对于“生成”过程是已知的,并且因此在没有过多的类相关开销的情况下实现结果,如果需要进行事后修改。

相关问题