下面的代码如何工作?
k = np.array([[ 0., 0.07142857, 0.14285714],
[ 0.21428571, 0.28571429, 0.35714286],
[ 0.42857143, 0.5, 0.57142857],
[ 0.64285714, 0.71428571, 0.78571429],
[ 0.85714286, 0.92857143, 1. ]])
y = np.array([[0, 3, 1, 2],
[2, 1, 0, 3]])
b = k[y]
形状是:
k shape: (5, 3)
y shape: (2, 4)
b shape: (2, 4, 3)
为什么 numpy 矩阵会接受另一个矩阵作为其索引,k 如何找到正确的输出?为什么要生成一个张量呢?
b的输出是
[[[ 0. 0.07142857 0.14285714]
[ 0.64285714 0.71428571 0.78571429]
[ 0.21428571 0.28571429 0.35714286]
[ 0.42857143 0.5 0.57142857]]
[[ 0.42857143 0.5 0.57142857]
[ 0.21428571 0.28571429 0.35714286]
[ 0. 0.07142857 0.14285714]
[ 0.64285714 0.71428571 0.78571429]]]
最佳答案
这叫做 integer array indexing .
Integer array indexing allows selection of arbitrary items in the array based on their N-dimensional index. Each integer array represents a number of indexes into that dimension.
示例 -
x = array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
rows = np.array([[0, 0],
[3, 3]], dtype=np.intp)
columns = np.array([[0, 2],
[0, 2]], dtype=np.intp)
x[rows, columns]
输出-
array([[ 0, 2],
[ 9, 11]])
在这种情况下,如您所见,我们通过给出元素的“坐标”来选择角元素。如果你尝试只给出一个 2d 矩阵它会像这样评估它 -
x[rows]
输出-
array([[[ 0, 1, 2],
[ 0, 1, 2]],
[[ 9, 10, 11],
[ 9, 10, 11]]])
关于python - Numpy:使用矩阵作为另一个矩阵的索引来创建张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38541860/