【问题标题】:what does np.eye(n)[nparray] mean? [duplicate]np.eye(n)[nparray] 是什么意思? [复制]
【发布时间】:2018-02-17 23:54:29
【问题描述】:

我将通过一些代码

y_enc = np.eye(21)[label]

其中 label 是形状为 (224, 224) 的 ndarray y_enc 是形状为 (224, 224, 21) 的 ndarray

即使打印了形状,我也无法理解这句话。 np.eye 应该生成一个维度为 21 x 21 的对角矩阵。它后面有 [label] 是什么意思?

【问题讨论】:

标签: numpy


【解决方案1】:

来自Documentationnumpy.eye

返回一个二维数组,其中对角线为 1,其他位置为 0。

例子:

>>np.eye(3)
array([[ 1.,  0.,  0.],
   [ 0.,  1.,  0.],
   [ 0.,  0.,  1.]])
>>> np.eye(3)[1]
array([ 0.,  1.,  0.])

[label] 是数组元素索引。所以只有一个元素,它返回给定数量的行元素作为数组。

>>> np.eye(3)[1]
array([ 0.,  1.,  0.])
>>> np.eye(3)[2]
array([ 0.,  0.,  1.])

因为它是 2d 数组,您还可以通过在 [row_index, column_index] 上提供 2 个索引号来访问特定元素

>>> np.eye(3)[2,1]
0.0
>>> np.eye(3)[2,2]
1.0
>>> np.eye(3)[1,1]
1.0

【讨论】:

  • 不要认为你很成功。 label 本身就是一个 adarray。不仅仅是索引列表。此外,标签方式的索引超过 21。正如我所说,y_enc 最终的形状为 (224, 224, 21)
  • 好的。而不是你如何解释这个错误。 >>> a=np.eye(21)[224,224,21] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: too many indices for array
  • 你没有回答问题,兄弟。试试这个并回答这个命令如何生成结果。 a = np.array([[2,0],[1,2]]);np.eye(3)[a].
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-10
  • 2019-09-12
  • 2015-01-22
  • 2012-01-03
  • 2020-10-27
  • 2015-07-15
相关资源
最近更新 更多