Reputation: 422
If I have a 3D Tensor (Variable) with size [a,b,c]. consider it as a b*c matrix, and I hope that all these a matrix got row normalized.
Upvotes: 8
Views: 21698
Reputation: 1
To normalize a matrix in such a way that the sum of each row is 1, simply divide by the sum of each row:
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))
Upvotes: 0
Reputation: 37691
The following should work.
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
Upvotes: 0
Reputation: 6547
You can use the normalize
function.
import torch.nn.functional as f
f.normalize(input, p=2, dim=2)
The dim=2
argument tells along which dimension to normalize (divide each row vector by its p-norm
.
Upvotes: 20