首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >与numpy.eye相比,使用numpy.identity有哪些优势?

与numpy.eye相比,使用numpy.identity有哪些优势?
EN

Stack Overflow用户
提问于 2015-02-06 18:19:24
回答 2查看 26.5K关注 0票数 56

看过numpyeyeidentity的手册页后,我假设identityeye的特例,因为它的选项更少(例如,eye可以填充移位的对角线,identity不能),但似乎可以更快地运行。然而,无论是在小数组还是大型数组上,情况都不是这样:

代码语言:javascript
复制
>>> 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的优势是什么呢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-06 18:30:53

identity只调用eye,所以在如何构造数组上没有区别。下面是identity的代码:

代码语言:javascript
复制
def identity(n, dtype=None):
    from numpy import eye
    return eye(n, dtype=dtype)

正如您所说,主要的区别是使用eye可以偏移对角线,而identity只填充主对角线。

由于单位矩阵在数学中是一个如此常见的构造,似乎使用identity的主要优势仅仅是因为它的名称。

票数 74
EN

Stack Overflow用户

发布于 2020-09-03 15:42:50

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

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28363447

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档