如何在不知道维度的情况下拼接张量?

huangapple go评论49阅读模式
英文:

How to splice a tensor without knowing the dimensions?

问题

如何以编程方式获得类似于 x[:, :48, ...] 的等效内容?

英文:

Say I had a tensor x of shape (21, 256, *), how could I get the equivalent of x[:, :48, ...] programmatically?

答案1

得分: 1

或者,您可以在纯Python中执行此操作,因为

```python
y = x[:, :48, ...]

等效于

y = x[[slice(None), slice(None, 48), Ellipsis]]

我们可以通过编程方式构建切片列表

dim = 1
slices = [slice(None)] * dim + [slice(None, 48)] + [Ellipsis]
y = x[slices]

请注意,省略号实际上不是必需的,因为x[:, :48]x[:, :48, ...]是等效的。


<details>
<summary>英文:</summary>

Alternatively, you could do this in pure python since

```python
y = x[:, :48, ...]

is equivalent to

y = x[[slice(None), slice(None, 48), Ellipsis]]

We can construct the list of slices programmatically

dim = 1
slices = [slice(None)] * dim + [slice(None, 48)] + [Ellipsis]
y = x[slices]

Note that the ellipsis isn't actually necessary because x[:, :48] and x[:, :48, ...] are equivalent.

答案2

得分: 0

以上问题的等效方法是使用 torch.index_select

indexes = torch.arange(48)
torch.index_select(myTensor, 1, indexes)
英文:

The equivalent for the above question would be to use torch.index_select:

indexes = torch.arange(48)
torch.index_select(myTensor, 1, indexes)

huangapple
  • 本文由 发表于 2023年2月27日 00:06:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573248.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定