【问题标题】:What are the advantages of using numpy.identity over numpy.eye?与 numpy.eye 相比,使用 numpy.identity 有什么优势?
【发布时间】:2015-04-06 10:59:48
【问题描述】:

查看了numpyeyeidentity 的手册页后,我认为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

那么,与eye 相比,使用identity 的优势是什么?

【问题讨论】:

    标签: python arrays performance numpy


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 你知道为什么很多张量库都把恒等式叫做eye吗?
    • @aeduG:好问题——我真的不知道。如果我不得不猜测,那只是因为单位矩阵通常用数学符号表示I,但是这个字母不能用于编程语言,因为它可能会与虚数单位混淆。 Ieye 是同音字,我想eyeidentity 更容易输入。
    【解决方案2】:

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

    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)
    

    【讨论】:

      【解决方案3】:

      np。 identity - 返回一个 SQUARE MATRIX(二维数组的特殊情况),它是一个单位矩阵,主对角线(即“k=0”)为 1,其他值为 0。你不能在这里改变对角线k

      np。 eye - 返回一个 2D-ARRAY,它填充对角线,即 'k' 可以设置为 1,其余为 0。

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

      但是,如果您需要特定形状/大小的 1 和 0 矩阵,或者可以控制对角线,则可以使用 eye 方法

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

      参考: https://numpy.org/doc/stable/reference/generated/numpy.identity.html [2]: http://ttps://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.eye.html [3]: https://www.hackerrank.com/challenges/np-eye-and-identity/problem

      【讨论】:

        猜你喜欢
        • 2010-09-24
        • 2010-12-27
        • 2013-05-09
        • 2017-05-29
        • 2017-11-24
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        相关资源
        最近更新 更多