Qinqing Liu
Qinqing Liu

Reputation: 422

How Pytorch do row normalization for each matrix in a 3D Tensor(Variable)?

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

Answers (3)

Xcode
Xcode

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

Wasi Ahmad
Wasi Ahmad

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

nyumerics
nyumerics

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

Related Questions