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 &quot;sum of elements of any rows be 1, by dividing sum of rows.&quot;
How can I make it? At first I thought I can do it by 'for' and 'append' command.
Is there any easier way?

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)

