使用 numpy.identity 比 numpy.eye 有什么优势?

What are the advantages of using numpy.identity over numpy.eye?

查看了 numpyeye and identity 的手册页后,我假设 identityeye 的特例,因为它有更少的选项(例如 eye 可以填充移动的对角线,identity 不能),但可能 运行 更快。但是,无论是小型阵列还是大型阵列都不是这种情况:

>>> np.identity(3)                                                  
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])
>>> np.eye(3)                                                       
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])
>>> timeit.timeit("import numpy; numpy.identity(3)", number = 10000)
0.05699801445007324
>>> timeit.timeit("import numpy; numpy.eye(3)", number = 10000)     
0.03787708282470703
>>> timeit.timeit("import numpy", number = 10000)                   
0.00960087776184082
>>> timeit.timeit("import numpy; numpy.identity(1000)", number = 10000)
11.379066944122314
>>> timeit.timeit("import numpy; numpy.eye(1000)", number = 10000)     
11.247124910354614

那么,使用 identity 相对于 eye 的优势是什么?

identity 只是调用 eye 所以数组的构造方式没有区别。这是 identity 的代码:

def identity(n, dtype=None):
    from numpy import eye
    return eye(n, dtype=dtype)

如您所说,主要区别在于 eye 可以偏移对角线,而 identity 仅填充主对角线。

由于单位矩阵是数学中如此常见的结构,使用 identity 的主要优势似乎仅在于其名称。

要查看示例中的差异,运行 下面的代码:

import numpy as np

#Creates an array of 4 x 4 with the main diagonal of 1

arr1 = np.eye(4)
print(arr1)

print("\n")

#or you can change the diagonal position

arr2 = np.eye(4, k=1)  # or try with another number like k= -2
print(arr2)

print("\n")

#but you can't change the diagonal in identity

arr3 = np.identity(4)
print(arr3)

np.identity returns 一个 方阵 (二维数组的特例),它是一个单位矩阵,其主对角线(即 'k=0') 为 1,其他值为 0。您不能在此处更改对角线 k

np.eye returns 一个 2D 数组,它填充对角线,即 'k' 可以设置,1 和其余带 0。

因此,主要优势取决于要求。如果你想要一个单位矩阵,你可以马上去 identity,或者可以调用 np.eye 将其余的保留为默认值。

但是,如果您需要特定 shape/size 的 1 和 0 矩阵或控制对角线,您可以使用 eye 方法。

就像矩阵是数组的特例一样,np.identitynp.eye 的特例。

其他参考资料: