我们知道,numpy的array和torch的tensor在很多方面性质一样,这里以array举例,生成一个新的试图。
通常而言,我们利用视图生成新的array时,每个维度对应的索引数是必须要相同,类似
>>>import numpy as np
>>>x = np.arange(60).reshape((3,4,5))
>>>x[[1,2],[2,3],[3,4]]
array([33, 59])
如果索引数不同,则会出错
>>>x[[1,2],[2,3],[0,1,2]]
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (2,) (2,) (3,)
而非通常的情况我了解的有两种:
和索引数为1的情况。
>>>x[[1,2],[2,3],[4]]
array([34, 59])
>>>x[[1,2],[2,3],:]
array([[30, 31, 32, 33, 34],
[55, 56, 57, 58, 59]])
>>>x[[1],[2,3],:]
array([[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39]])
可以看出,对于维度为1和维度为全部的情况,可以兼容各种维度的情况。