【发布时间】:2018-05-04 12:33:16
【问题描述】:
如果我有一个大小为 [a,b,c] 的 3D 张量(变量)。 将其视为 b*c 矩阵,我希望所有这些矩阵都得到行归一化。
【问题讨论】:
如果我有一个大小为 [a,b,c] 的 3D 张量(变量)。 将其视为 b*c 矩阵,我希望所有这些矩阵都得到行归一化。
【问题讨论】:
您可以使用normalize 函数。
import torch.nn.functional as f
f.normalize(input, p=2, dim=2)
dim=2 参数说明要规范化的维度(将每个行向量除以其 p-norm。
【讨论】:
p=1,此答案将平方和设置为 1(L2 范数)。
以下应该可以工作。
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
【讨论】:
要以每行之和为 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))
【讨论】: