Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.linalg.norm function

PyTorch torch.linalg.norm function


PyTorch torch reference manual PyTorch torch reference manual

torch.linalg.norm is a function in PyTorch's linear algebra module used to compute the norm of a matrix or vector. It supports many norm types, such as L1, L2, and Frobenius norms.

Function definition

torch.linalg.norm(A, ord=None, dim=None, keepdim=False, out=None, dtype=None)

Parameters:

Return Value:


Usage examples

Example - Frobenius norm

import

torch

Create a matrix

A

=

torch.

tensor

(

[

[

1.0

,

2.0

]

,

[

3.0

,

4.0

]

]

)

Frobenius norm

norm_fro

=

torch.

linalg

.

norm

(

A

)

print

(

"Matrix A:"

)

print

(

A

)

print

(

"Frobenius norm:"

,

norm_fro

)

The output is:

矩阵 A:

tensor([[1., 2.],

        [3., 4.]])

Frobenius 范数: tensor(5.4772)

Example - vector L2 norm

import

torch

Create a vector

v

=

torch.

tensor

(

[

3.0

,

4.0

]

)

L2 norm (default)

norm_l2

=

torch.

linalg

.

norm

(

v

)

L1 norm

norm_l1

=

torch.

linalg

.

norm

(

v

,

ord

=

1

)

print

(

"Vector v:"

,

v

)

print

(

"L2 norm:"

,

norm_l2

)

print

(

"L1 norm:"

,

norm_l1

)


PyTorch torch reference manual PyTorch torch reference manual