[英]Python numpy array indexing. How is this working?
I came across this python code (which works) and to me it seems amazing. 我遇到了这个python代码(有效),在我看来,这太神奇了。 However, I am unable to figure out what this code is doing.
但是,我无法弄清楚这段代码在做什么。 To replicate it, I sort of wrote a test code:
为了复制它,我编写了一个测试代码:
import numpy as np
# Create a random array which represent the 6 unique coeff.
# of a symmetric 3x3 matrix
x = np.random.rand(10, 10, 6)
So, I have 100 symmetric 3x3 matrices and I am only storing the unique components. 因此,我有100个对称3x3矩阵,并且只存储唯一的分量。 Now, I want to generate the full 3x3 matrix and this is where the magic happens.
现在,我想生成完整的3x3矩阵,这就是魔术发生的地方。
indices = np.array([[0, 1, 3],
[1, 2, 4],
[3, 4, 5]])
I see what this is doing. 我知道这是怎么回事。 This is how the 0-5 index components should be arranged in the 3x3 matrix to have a symmetric matrix.
这就是0-5索引分量应如何在3x3矩阵中排列以具有对称矩阵的方式。
mat = x[..., indices]
This line has me lost. 这条线让我迷路了。 So, it is working on the last dimension of the x array but it is not at all clear to me how the rearrangement and reshaping is done but this indeed returns an array of shape (10, 10, 3, 3).
因此,它正在x数组的最后一个维度上工作,但我完全不清楚如何完成重新排列和重塑,但这确实返回了形状数组(10、10、3、3)。 I am amazed and confused!
我感到惊讶和困惑!
From the advanced indexing documentation - bi rico's link. 来自高级索引文档-bi rico的链接。
Example
例
Suppose x.shape is (10,20,30) and ind is a (2,3,4)-shaped indexing intp array, thenresult = x[...,ind,:] has shape (10,2,3,4,30) because the (20,)-shaped subspace has been replaced with a (2,3,4)-shaped broadcasted indexing subspace.
假设x.shape为(10,20,30)并且ind为(2,3,4)形索引intp数组,则结果= x [...,ind ,:]的形状为(10,2,3, 4,30),因为(20,)形状的子空间已被(2,3,4)形状的广播索引子空间替换。 If we let i, j, kloop over the (2,3,4)-shaped subspace then result[...,i,j,k,:] =x[...,ind[i,j,k],:].
如果我们让(i,j,kloop)在(2,3,4)形子空间上,则结果为[...,i,j,k ,:] = x [...,ind [i,j,k] ,:]。 This example produces the same result as x.take(ind, axis=-2).
本示例产生的结果与x.take(ind,axis = -2)相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.