【问题标题】:Is there a verctorized approach in PyTorch to get this result?PyTorch 中是否有一种verctorized 方法来获得这个结果?
【发布时间】:2021-08-11 09:40:38
【问题描述】:

我想用 torch 函数得到这个结果。你有什么建议吗?

import torch
test_tensor=torch.tensor([[1,  2,  3, 4,  5,  6],
                         [7,  8,  9, 10,  11,  12]]
                        )
print(test_tensor)
'''
I would like to get:
t_1 = torch.tensor([[6], #1+2+3
                  [24]])#7+8+9
t_2 = torch.tensor([[9], #1+3+5
                  [27]])#7+9+11
'''

【问题讨论】:

    标签: python python-3.x pytorch


    【解决方案1】:

    使用standard Python stride notation

    import torch
    test_tensor=torch.tensor([[1,  2,  3, 4,  5,  6],
                             [7,  8,  9, 10,  11,  12]]
                            )
    
    t1 = test_tensor[:, :3].sum(dim=1)
    print(t1)
    t2 = test_tensor[:, ::2].sum(dim=1)
    print(t2)
    

    【讨论】:

    • 谢谢@Gulzar 有没有类似的方法可以得到 t_3 = torch.tensor([[14], #1+2+5+6 [38]])#7+8+11+ 12 ?- 模式是:将两个元素相加并跳过两个元素到张量行的末尾
    • this,也许会得到答复。在此之前,请尝试使用掩码:mask = torch.ones_like(t, dtype=torch.bool)mask[:, 2:4]=0t3_temp=torch.tensor(t)t3_temp[mask]=t[mask]t3=t3_temp.sum(dim=1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2021-05-07
    • 1970-01-01
    相关资源
    最近更新 更多