Why do we use .pow(2) and not **2?

In some cases, the member function (x.pow()) is more elegant than the expression mode (x**2). Given a tensor a defined as:

a = torch.tensor([1, 2, 3]).

Calling a member function like

a.pow(2).mean()

should be cleaner than

(a**2).mean().

Calling member function is object oriented while bracket turn the expression it into a more functional style programming.
Following case might be rare but shows the advantages more clearly:

((a**2).add(1)**2).mean()

vs

a.pow(2).add(1).pow(2).mean()

As the expression gets more complicated, member function shows more advantages.

4 Likes