Search code examples
pythonnumpypytorchtensor

Center a tensor in pytorch


Cantering means shifting a vector so that its mean will be zero.

I want to center each row of a tensor, for example:

A = |1 , 1|    A_center = |0, 0|
    |0 , 4|               |-2,2|

For this, I use this approach:

a_center  = a - a.mean(dim=1).unsqueeze(1)

I want to know if there is any built-in way to center a tensor in PyTorch. Because I know there are built-in functions for length normalization, I assume there might be a function for tensor centering too, but I wasn't able to find it.


Solution

  • Until now there is no built-in function in Pytorch. Use this:

    x_centered = x - x.mean(dim=1, keepdim=True)