【问题标题】:advanced 3d indexind in theanotheano 中的高级 3d indexind
【发布时间】:2016-08-21 22:31:27
【问题描述】:

我的问题与 Indexing tensor with index matrix in theano? 除了我有 3 个维度。起初我想让它在 numpy 中工作。二维没有问题:

>>> idx = np.random.randint(3, size=(4, 2, 3))
>>> d = np.random.rand(4*2*3).reshape((4, 2, 3))
>>> d[1]
array([[ 0.37057415,  0.73066383,  0.76399376],
       [ 0.12155831,  0.12552545,  0.87648523]])
>>> idx[1]
array([[2, 0, 1],
       [2, 2, 2]])
>>> d[1][np.arange(d.shape[1])[:, np.newaxis], idx[1]]
array([[ 0.76399376,  0.37057415,  0.73066383],
       [ 0.87648523,  0.87648523,  0.87648523]])  #All correct

但我不知道如何使它适用于所有 3 个维度。失败尝试示例:

>>> d[np.arange(d.shape[0])[:, np.newaxis], np.arange(d.shape[1]), idx]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (4,1) (2,) (4,2,3) 

【问题讨论】:

    标签: python numpy indexing slice


    【解决方案1】:

    这行得通吗?

    d[
        np.arange(d.shape[0])[:, np.newaxis, np.newaxis],
        np.arange(d.shape[1])[:, np.newaxis],
        idx
    ]
    

    您需要索引数组共同具有可广播的维度

    【讨论】:

    • 谢谢,没错。我保证尝试了解它是如何工作的)
    猜你喜欢
    • 2016-10-30
    • 1970-01-01
    • 2018-01-15
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多