英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论