How could i calculate 2-norm in batches

For example,there are 3 two-dimensional matrices. And it’s shape is [3,2,2]
Of course, i could calculate their 2-norm by this way:

x = torch.randn(3, 2, 2)
for i in range(x.shape[0]):
print(torch.norm(x[i], 2))

and it’s output is

This is a solution. Well, as we all know the for-looping is inefficientis. and could pytorch calculate their 2-norm without using for-looping?

You can pass multiple dimensions to the norm operation:

x.norm(dim=[1, 2])
> tensor([2.3191, 1.7451, 2.1392])
1 Like

Thank you very much!