简体   繁体   English

索引时如何解包元组?

[英]How to unpack a tuple when indexing?

I have a very high dimensional tensor, say A with shape 5 X 10 X 100 X 200 X 50. I have a some numpy expression that returns a tuple T, containing indices of elements that I want to extract from A.我有一个非常高维的张量,比如形状为 5 X 10 X 100 X 200 X 50 的 A。我有一个返回元组 T 的 numpy 表达式,其中包含我想从 A 中提取的元素的索引。

I'm trying this:我正在尝试这个:

A[*T]

It says:它说:

invalid syntax, you cannot use starred expressions here.语法无效,您不能在此处使用星号表达式。

How can I do it?我该怎么做? PS: The long solution is: A[T[0], T[1], T[2], T[3], T[4]] PS:长解是:A[T[0], T[1], T[2], T[3], T[4]]

EDIT: I just found that there is no need to do that as it is being done automatically.编辑:我刚刚发现没有必要这样做,因为它是自动完成的。 Example:例子:

a= np.random.rand(3,3)
a[np.triu_indices(3)]

The expression np.triu_indices(3) is being unpacked automatically when passed to a as index.表达式np.triu_indices(3)在传递给a作为索引时会自动解包。 However , going back to my question it is not happening.但是,回到我的问题并没有发生。 To be concrete, here's an example:具体来说,这里有一个例子:

a = np.random.rand(100, 50, 14, 14)
a[:, :, np.triu_indices(14)].shape

Supposedly, the last bit np.triu_indices(14) should act on last two axes, as in the previous example, but it is not happening, and the shape resulting is weird.假设最后一位np.triu_indices(14)应该作用在最后两个轴上,就像前面的例子一样,但它没有发生,并且结果的形状很奇怪。 Why isn't being unpacked?为什么不拆包? and how to do that?以及如何做到这一点?

The problem with:问题在于:

a[:, :, np.triu_indices(14)]

is that you are using as argument for [] a tuple of mixed types slice and tuple ( tuple(slice, slice, tuple(np.ndarray, np.ndarray)) ) and not a single tuple (eventually with advanced indexing), eg tuple(slice, slice, np.ndarray, np.ndarray) .是你使用作为参数[]混合类型的元组slicetupletuple(slice, slice, tuple(np.ndarray, np.ndarray)) )而不是单个tuple (最终具有高级索引),例如tuple(slice, slice, np.ndarray, np.ndarray) This is causing your troubles.这给你带来了麻烦。 I would not go into the details of what is happening in your case.我不会详细说明您的情况。

Changing that line to:将该行更改为:

a[(slice(None),) * 2 + np.triu_indices(14)]

will fix your issues:将解决您的问题:

a[(slice(None),) * 2 + np.triu_indices(14)].shape
# (100, 50, 105)

Note that there are a couple of ways for rewriting:请注意,有几种重写方法:

(slice(None),) * 2 + np.triu_indices(14)

another way may be:另一种方式可能是:

(slice(None), slice(None), *np.triu_indices(14))

Also, if you want to use the ... syntax, you need to know that ... is syntactic sugar for Ellipsis , so that:此外,如果您想使用...语法,您需要知道...Ellipsis的语法糖,因此:

(Ellipsis,) + np.triu_indices(14)

or:或者:

(Ellipsis, *np.triu_indices(14))

would work correctly:会正常工作:

a[(Ellipsis,) + np.triu_indices(14)].shape                                                   
# (100, 50, 105)
a[(Ellipsis, *np.triu_indices(14))].shape                                                   
# (100, 50, 105)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM