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

What is the purpose and utility of the subok option in numpy.zeros_like()?

利用numpy的zeros_like及相关函数,有一个选项

subok: bool, optional.

numpy.zeros_like(a, dtype=None, order='K', subok=True)

If True, then the newly created array will use the sub-class type of ‘a’, otherwise it will be a base-class array. Defaults to True.

我假设所有 numpy 数组都是 class ndarray 并且我从来不需要详细查看数组的 subclass。在什么情况下我可能想选择不使用相同的 subclass,指定使用 baseclass?

What is the purpose and utility ... ?

目的:

调用签名帮助传递已处理的实例类型,如下所示:

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

相反,如果不愿意"reprocess"既.shape又实例化相同的class,使用subok = False,生成的 *_alike() 将不会得到相同的 class,因为 "example" 过程是为了生成 *_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-flags 在更多 numpy 函数中很常见(不仅是 *_like()-s,也在 np.array( ... ) 中),出于同样的目的,因为它对于智能类型修改代码设计非常有用,其中所需的产品类型是 "generating" 过程已知的,因此可以在没有过度 class 相关开销的情况下实现结果,如果前post 否则需要修改。