Skip to main content
 首页 » 编程设计

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

2024年09月07日9bhlsheji

使用 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 数组都是 ndarray 类,而且我从来不需要详细查看数组的子类。在什么情况下我可能希望选择不使用相同的子类,指定使用基类?

请您参考如下方法:

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 

相反,如果不愿意“重新处理” .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-flags 在更多 numpy 函数中很常见(不仅是 *_like()-s,也在 np.array( ... ) ),出于同样的目的,因为它对于智能类型修改代码设计非常有用,其中所需的产品类型为“生成”过程和因此,如果需要事后修改,则无需过多的类相关开销即可实现结果。