pytorch - Pytorch - 索引一系列多个索引?
问题描述
假设我有一个大小为 [100, 100] 的张量,我有一组大小为 [100]的start_indices
和end_indices
我希望能够做这样的事情:
tensor[start_indices:end_indices, :] = 0
不幸的是,我收到一条错误消息
TypeError: only integer tensors of a single element can be converted to an index
那么,如果没有 for 循环,这实际上可能吗?
解决方案
据我所知,如果没有某种循环或列表理解,这是不可能的。
以下是一些可能有用的替代方案,具体取决于您的用例。特别是如果您希望重复使用相同的任务start_indices
并end_indices
进行多个分配,或者如果您希望只有一个就地分配,tensor
那么下面的解决方案将很有用。
例如,如果您获得了索引列表,start_indices
而不是end_indices
row_indices = torch.cat([torch.arange(s, e, dtype=torch.int64) for s, e in zip(start_indices, end_indices)])
那么这可以使用
tensor[row_indices, :] = 0
或者如果给你一个面具
mask = torch.zeros(tensor.shape, dtype=torch.bool, device=tensor.device)
for s, e in zip(start_indices, end_indices):
mask[s:e, :] = True
那么这可以使用
tensor[mask] = 0
推荐阅读
- android - 使用 setTosAndPrivacyPolicyUrls 的 Firebase 身份验证不提供可点击的链接
- python - SQL:在不创建新记录的情况下将 Update 与 Select 和 Insert 一起使用以插入数据?这是可能的?备择方案?
- java - 添加
通过while循环在hashmap中但不工作 - python - 重新启动内核时等待 kernel_info_reply 超时
- azure-devops - 在 Azure Pipeline 期间触发数据库更新
- javascript - 使用 Chart.js 版本 3,如何在堆积条形图上左对齐 y 轴标签?
- javascript - jQuery事件未附加到输入字段
- html - 响应表中的输入字段不够宽
- swift - 共享 Carthage 依赖项时 Xcode 控制台中的 po 不起作用
- snowflake-cloud-data-platform - 在 Snowflake 中使用内联值的视图