使用 einsum

问题描述

我只设法使用 Numpy einsum 提取了一条对角线。如何在 einsum 的帮助下获得 [6,37,68,99] 等其他对角线?

x =  np.arange(1,26 ).reshape(5,5)
y =  np.arange(26,51).reshape(5,5)
z =  np.arange(51,76).reshape(5,5)
t =  np.arange(76,101).reshape(5,5)
p =  np.arange(101,126).reshape(5,5)

a4 = np.array([x,y,z,t,p]

提取一条对角线:

>>>np.einsum('iii->i',a4)
>>>[  1  32  63  94 125]

解决方法

我没有使用 einsum 的任何“简单”解决方案,但使用 for 循环非常简单:

import numpy as np

# Generation of a 3x3x3 matrix
x =  np.arange(1,10).reshape(3,3)
y =  np.arange(11,20).reshape(3,3)
z =  np.arange(21,30).reshape(3,3)

M = np.array([x,y,z])

# Generation of the index
I = np.arange(0,len(M))

# Generation of all the possible diagonals
for ii in [1,-1]:
    for jj in [1,-1]:
        print(M[I[::ii],I[::jj],I])

# OUTPUT:
# [ 1 15 29]
# [ 7 15 23]
# [21 15  9]
# [27 15  3]

我们修复最后一个维度的索引,并找到其他维度的向后和向前索引的所有可能组合。

,

您是否意识到这个 einsum 与:

In [64]: a4=np.arange(1,126).reshape(5,5,5)
In [65]: i=np.arange(5)
In [66]: a4[i,i,i]
Out[66]: array([  1,32,63,94,125])

调整索引以获得其他对角线应该很容易。

In [73]: a4[np.arange(4),np.arange(1,5),np.arange(4)]
Out[73]: array([ 6,37,68,99])

产生主对角线的`iii->i'与其说是设计的特征,不如说是一个快乐的意外。不要试图推动它。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...