看过numpy
的eye
和identity
的手册页后,我假设identity
是eye
的特例,因为它的选项更少(例如,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
那么,相对于eye
,使用identity
的优势是什么呢
发布于 2015-02-06 18:30:53
identity
只调用eye
,所以在如何构造数组上没有区别。下面是identity
的代码:
def identity(n, dtype=None):
from numpy import eye
return eye(n, dtype=dtype)
正如您所说,主要的区别是使用eye
可以偏移对角线,而identity
只填充主对角线。
由于单位矩阵在数学中是一个如此常见的构造,似乎使用identity
的主要优势仅仅是因为它的名称。
发布于 2020-09-03 15:42:50
要查看示例中的差异,请运行以下代码:
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)
https://stackoverflow.com/questions/28363447
复制相似问题