python - Numpy:使用矩阵作为另一个矩阵的索引来创建张量?

标签 python numpy matrix

下面的代码如何工作?

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/

相关文章:

python - 列表中的 bin 顺序值

matlab - 使用索引矩阵检索具有否定精确索引的矩阵元素?

c++ - 如何将矩阵因式分解为核矩阵的乘积?

python - Django:model.objects.create() 更改了之前的 model.objects.filter() 的结果集

如果 streams=True,Python Requests 模块不处理超时?

Python 库 - json 到 json 的转换

matlab - 在 Matlab 中对序列进行分类的隐马尔可夫模型

python - 如何在 Python Pandas 中重命名索引行?

python - 如何在 Ubuntu 11.10 Oneiric 中正确安装 python-numpy

python - 定义 Numpy 数组并在单行中赋值