【问题标题】:Summing Torch tensor based on another tensor基于另一个张量求和 Torch 张量
【发布时间】:2021-11-10 11:11:35
【问题描述】:

我有两个张量,其中第一个包含浮点数,第二个包含 0 和 1。 我想根据第二个张量对第一个张量求和。更具体地说,我想在两个 0 的出现之间求和。 例如,考虑

a = tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
b = tensor([0., 1., 1., 1., 0., 1., 1., 1., 1., 0.])

我想要一些矢量化(最好是)接收两个张量并返回的操作

c = tensor([4., 5., 1.] 

c 只是张量 a 的元素之和,在张量 b 中出现的两个 0 之间。

【问题讨论】:

    标签: python vectorization torch


    【解决方案1】:

    您可以使用torch.tensor_split 将您的张量拆分为 b 中 0 的索引,然后将它们分别求和:

    例如:

    a = tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
    b = tensor([0., 1., 1., 1., 0., 1., 1., 1., 1., 0.])
    group = torch.tensor_split(a, torch.where(b==0)[0])
    # Output:
    # (tensor([]),
    # tensor([1., 1., 1., 1.]),
    # tensor([1., 1., 1., 1., 1.]),
    # tensor([1.]))
    
    individual_sum = list(map(torch.sum, group))  # You can use loop/list comprehension etc
    # Output
    # [tensor(0.), tensor(4.), tensor(5.), tensor(1.)]
    

    请注意,第一个 0 也被考虑在内,并导致拆分后的张量为空。您可以在组合时删除它

    torch.tensor(individual_sum[1:])
    # Output
    # tensor([4., 5., 1.])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 2021-06-27
      • 2016-07-02
      • 1970-01-01
      • 2016-03-21
      • 2017-09-11
      • 2019-07-23
      相关资源
      最近更新 更多