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

问题描述 投票:1回答:1

使用numpy的zeros_like和相关函数,有一个选项

测试:bool,可选。

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

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

我假设所有numpy数组都是类ndarray,我从来没有必要仔细查看数组的子类。在什么情况下我可能想要选择不使用相同的子类,请指定基类的使用?

python class numpy subclass
1个回答
2
投票

目的和用途是什么......?

目的:

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

>>> 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( ... ))中很常见,出于同样的目的,因为它对于智能类型修改代码设计非常有用,其中所需类型的产品是已知的如果需要事后修改,则可以实现“生成”过程,并且无需过度的类相关开销就可以实现结果。

© www.soinside.com 2019 - 2024. All rights reserved.