Python 使用相同大小的索引张量拆分火炬张量
假设我有张量Python 使用相同大小的索引张量拆分火炬张量,python,indexing,pytorch,tensor,torch,Python,Indexing,Pytorch,Tensor,Torch,假设我有张量 t = torch.tensor([1,2,3,4,5]) 我想用一个相同大小的索引张量来拆分它,它告诉我每个元素应该在哪个方向拆分 indices = torch.tensor([0,1,1,0,2]) 所以最终的结果是 splits [tensor([1,4]), tensor([2,3]), tensor([5])] 在Pytorch中有没有一种简洁的方法可以做到这一点 编辑:通常会有2到3个以上的拆分。使用逻辑索引确实是可行的,您只需确保索引“掩码”由布尔值构成,因此
t = torch.tensor([1,2,3,4,5])
我想用一个相同大小的索引张量来拆分它,它告诉我每个元素应该在哪个方向拆分
indices = torch.tensor([0,1,1,0,2])
所以最终的结果是
splits
[tensor([1,4]), tensor([2,3]), tensor([5])]
在Pytorch中有没有一种简洁的方法可以做到这一点
编辑:通常会有2到3个以上的拆分。使用逻辑索引确实是可行的,您只需确保索引“掩码”由布尔值构成,因此在您的情况下
splits = t[indices > 0] , t[indices < 1]
splits=t[指数>0],t[指数<1]
或者,您也可以先将张量
索引转换为布尔数据类型。使用逻辑索引确实是可行的,您只需确保索引“掩码”是由布尔值生成的,因此在您的情况下
splits = t[indices > 0] , t[indices < 1]
splits=t[指数>0],t[指数<1]
或者,您可以先将张量索引转换为布尔数据类型。对于一般情况,可以使用argsort
进行转换:
def mask_split(tensor, indices):
sorter = torch.argsort(indices)
_, counts = torch.unique(indices, return_counts=True)
return torch.split(t[sorter], counts.tolist())
mask_split(t, indices)
如果这是您真正的用例,那么使用@Defirr-answer可能会更好(而且列表理解也可能更快,因为它不需要排序),类似这样:
def mask_split(tensor, indices):
unique = torch.unique(indices)
return [tensor[indices == i] for i in unique]
对于一般情况,可以使用argsort
:
def mask_split(tensor, indices):
sorter = torch.argsort(indices)
_, counts = torch.unique(indices, return_counts=True)
return torch.split(t[sorter], counts.tolist())
mask_split(t, indices)
如果这是您真正的用例,那么使用@Defirr-answer可能会更好(而且列表理解也可能更快,因为它不需要排序),类似这样:
def mask_split(tensor, indices):
unique = torch.unique(indices)
return [tensor[indices == i] for i in unique]
除其他答案外,对于pytorch中的索引,您可以直接使用索引位置访问这些元素:
t = torch.tensor([1,2,3,4])
print(t[[0,1,3]])
所以你不需要为索引存储张量。如果需要,您仍然可以存储带有1和0的numpy数组,然后从该数组中查找访问索引:
a = np.array([0, 1, 1, 0])
ind_ones = np.argwhere(a == 1).squeeze()
ind_zers = np.argwhere(a == 0).squeeze()
print(t[ind_ones]) # tensor([2, 3])
print(t[ind_zers]) # tensor([1, 4])
除其他答案外,对于pytorch中的索引,您可以直接使用索引位置访问这些元素:
t = torch.tensor([1,2,3,4])
print(t[[0,1,3]])
所以你不需要为索引存储张量。如果需要,您仍然可以存储带有1和0的numpy数组,然后从该数组中查找访问索引:
a = np.array([0, 1, 1, 0])
ind_ones = np.argwhere(a == 1).squeeze()
ind_zers = np.argwhere(a == 0).squeeze()
print(t[ind_ones]) # tensor([2, 3])
print(t[ind_zers]) # tensor([1, 4])