【问题标题】:How Pytorch do row normalization for each matrix in a 3D Tensor(Variable)?Pytorch 如何对 3D 张量(变量)中的每个矩阵进行行归一化?
【发布时间】:2018-05-04 12:33:16
【问题描述】:

如果我有一个大小为 [a,b,c] 的 3D 张量(变量)。 将其视为 b*c 矩阵,我希望所有这些矩阵都得到行归一化。

【问题讨论】:

    标签: torch pytorch tensor


    【解决方案1】:

    您可以使用normalize 函数。

    import torch.nn.functional as f
    f.normalize(input, p=2, dim=2)
    

    dim=2 参数说明要规范化的维度(将每个行向量除以其 p-norm

    【讨论】:

    • 我试过了,但行总和不是 1。不过,谢谢。我也试过 renorm 功能,它也不起作用。
    • 您介意用无法提供输出的最小工作示例的详细信息更新问题吗?到时候我会更好地进行修改。
    • @QinqingLiu 如果您希望行总和等于 1(L1 范数),您可以设置 set p=1,此答案将平方和设置为 1(L2 范数)。
    【解决方案2】:

    以下应该可以工作。

    import torch
    import torch.nn.functional as f
    
    a, b, c = 10, 20, 30
    
    t = torch.rand(a, b, c)
    g = f.normalize(t.view(t.size(0), t.size(1) * t.size(2)), p=1, dim=1)
    print(g.sum(1)) # it confirms the normalization
    
    g = g.view(*t.size())
    print(g) # get the normalized output vector of shape axbxc
    

    【讨论】:

      【解决方案3】:

      要以每行之和为 1 的方式对矩阵进行归一化,只需除以每行之和即可:

      import torch
      a, b, c = 10, 20, 30
      t = torch.rand(a, b, c)
      t = t / (torch.sum(t, 2).unsqueeze(-1))
      print(t.sum(2))
      

      【讨论】:

        猜你喜欢
        • 2020-06-05
        • 2019-12-03
        • 2018-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多