JAEMTO
JAEMTO

Reputation: 219

How can I make all rows of matrix sum 1 from tensor in pytorch

I have a matrix, which is from Cora.

The size of it is [2708,1433]

For any rows, the elements are 1 or 0. I want to make "sum of elements of any rows be 1, by dividing sum of rows."

How can I make it? At first I thought I can do it by 'for' and 'append' command.

Is there any easier way?

Upvotes: 0

Views: 2329

Answers (1)

KonstantinosKokos
KonstantinosKokos

Reputation: 3453

xs = xs / xs.sum(dim=-1).unsqueeze(-1)

If xs is your Tensor, xs.sum(dim=-1) is the summation over the column-index (i.e. a Tensor of shape (2708,). By unsqueezing it, you turn it into a matrix of shape (2708, 1) which you can then broadcast against xs. The result of the division is a matrix, all rows of which sum to 1:

xs.sum(dim=1)
assert torch.allclose(torch.ones(xs.shape[0], dtype=float), xs.sum(dim=1))

ps: if xs is ones and zeros, you might need to cast it to float first:

xs = xs.to(float)

Upvotes: 1

Related Questions