L1 Norm, L2 Norm, Squared L2 Norm, Infinity Norm 한 번에 정리하기 : Numpy, TensorFlow, PyTorch 에서 사용하기

2024. 7. 16. 07:02·Machine Learning Math/Linear Algebra
반응형

L1 Norm

L1 Norm은 벡터의 각 성분의 절대값의 합으로 정의된다.

 

$\| \mathbf{x} \|_1 = \sum_{i=1}^{n} |x_i|$

 

예를 들어 $[10,-3,2]$의 L1 Norm은 15이다.

 

장점

  • L1 Norm은 0과 0이 아닌 값 사이의 차이를 직관적으로 나타낸다. 벡터의 각 성분이 조금이라도 0에서 멀어지면 L1 Norm 값도 바로 변화하기 때문이다.

 

L2 Norm

L2 Norm은 벡터의 각 원소의 제곱의 합의 제곱근으로 정의된다. 유클리드 거리라고도 불리며, 다음과 같은 수식으로 표현된다.

 

$\| \mathbf{x} \|_2 = \sqrt{\sum_{i=1}^{n} x_i^2}$

 

예를 들어 $[3,4]$의 L2 Norm은 5이다.

 

장점

  • 벡터의 실제 물리적 길이를 나타내므로 직관적이다.

 

 

Squared L2 Norm

Squared L2 Norm은 각 원서의 제곱의 합으로 표현된다. 즉, L2 Norm의 제곱과 같으며, 다음과 같은 수식으로 표현된다.

 

$\| \mathbf{x} \|_2^2 = \sum_{i=1}^{n} x_i^2$

 

예를 들어 $[3,4]$의 L2 Norm은 $3^2+4^2=25$이다

 

장점

  • 제곱근을 계산할 필요가 없으므로 계산에 적은 비용이 든다.
  • $\mathbf{X}^T \mathbf{X}$ 를 계산하면 Squared L2 Norm 값이 된다.
  • 모든 점에서 미분 가능해 최적화에 유리하다.
  • L2 Norm은 특정 원소로 미분 시에 모든 원소를 고려해야 하지만, Squared L2 Norm은 미분 시에 원소 하나만 고려하면 된다.
  •  

단점

  • 데이터의 이상치나 잡음에 민감하다.
  • 원점(영점) 근처에서 천천히 증가한다. 이로 인해 이는 0과 0에 가까운 값을 구분하는 것이 중요한 경우에 사용할 수 없다.

 

 

Infinity Norm(Max Norm)

벡터 성분의 절대값 중 가장 큰 값으로 정의된다. 수식은 다음과 같다.

 

$\| \mathbf{x} \|_\infty = \max_{i} |x_i|$

 

예를 들어 $[3,4]$의 Infinity Norm은 4이다.

 

장점

  • 최대 절대값을 찾는 연산이어서 계산이 단순하다.
  • 하나의 성분에만 의존하므로 일부 성분이 큰 값을 가져도 전체 벡터에 큰 영향을 주지 않는다.

 

단점

  • 실제 벡터의 전체적인 크기를 직관적으로 나타내지 않는다.

 

Numpy 사용해 L1, L2, Squared L2, Infinity Norm 구하기

Numpy를 사용하면 다음과 같이 각 Norm을 구할 수 있다.

import numpy as np

# L1 Norm
x = np.array([10, -3, 2])
l1_norm = np.linalg.norm(x, 1)
print("L1 Norm:", l1_norm)

# L2 Norm
x = np.array([3, 4])
l2_norm = np.linalg.norm(x)
print("L2 Norm:", l2_norm)

# Squared L2 Norm
squared_l2_norm = np.sum(np.square(x))
print("Squared L2 Norm:", squared_l2_norm)

# Infinity Norm
inf_norm = np.linalg.norm(x, np.inf)
print("Infinity Norm:", inf_norm)

 

위 코드를 실행해보면 다음과 같은 결과가 나온다.

 

 

 

TensorFlow 사용해 L1, L2, Squared L2, Infinity Norm 구하기

TensorFlow를 사용하면 다음과 같이 각 Norm을 구할 수 있다.

import tensorflow as tf

# L1 Norm
x = tf.Variable([10.0, -3.0, 2.0])
l1_norm = tf.norm(x, ord=1)
print("L1 Norm:", l1_norm)

# L2 Norm
x = tf.constant([3.0, 4.0])
l2_norm = tf.norm(x)
print("L2 Norm:", l2_norm)

# Squared L2 Norm
squared_l2_norm = tf.reduce_sum(tf.square(x))
print("Squared L2 Norm:", squared_l2_norm)

# Infinity Norm
inf_norm = tf.norm(x, ord=np.inf)
print("Infinity Norm:", inf_norm)

 

위 코드를 실행해보면 결과는 다음과 같다.

 

 

 

Pytorch 사용해 L1, L2, Squared L2, Infinity Norm 구하기

Pytorch를 사용하면 다음과 같이 각 Norm을 구할 수 있다.

import torch

# L1 Norm
x = torch.tensor([10.0, -3.0, 2.0])
l1_norm = torch.norm(x, p=1)
print("L1 Norm:", l1_norm.item())

# L2 Norm
x = torch.tensor([3.0, 4.0])
l2_norm = torch.norm(x)
print("L2 Norm:", l2_norm)

# Squared L2 Norm
squared_l2_norm = torch.sum(x ** 2)
print("Squared L2 Norm:", squared_l2_norm)

# Infinity Norm
inf_norm = torch.norm(x, p=float('inf'))
print("Infinity Norm:", inf_norm)

 

위 코드를 실행해보면 결과는 다음과 같다.

 

 

norm 함수와 관련된 자료

1l TensorFlow의 norm 함수와 관련된 자료는 다음에서 찾을 수 있다.

https://www.tensorflow.org/api_docs/python/tf/norm

 

tf.norm  |  TensorFlow v2.16.1

Computes the norm of vectors, matrices, and tensors.

www.tensorflow.org

 

2. Pytorch의 norm 함수와 관련된 자료는 다음 링크에서 찾을 수 있다.

https://pytorch.org/docs/stable/generated/torch.norm.html

 

torch.norm — PyTorch 2.3 documentation

Shortcuts

pytorch.org

 

반응형
저작자표시 비영리 변경금지 (새창열림)

'Machine Learning Math > Linear Algebra' 카테고리의 다른 글

Tensor 사칙 연산, 아다마르 곱셈(Hadamard Product) 한 번에 정리하기: Numpy, TensorFlow, PyTorch에서의 사용법 정리  (0) 2024.07.18
기저 벡터(Basis Vector)와 직교 벡터(Orthogonal Vector)  (1) 2024.07.17
L2 Norm과 Unit Vector 알아보기 : Numpy, TensorFlow, PyTorch의 Norm 연산과 Unit Vector  (0) 2024.07.15
벡터 전치(Vector Transposition) 알아보기: Tensorflow, Pytorch, Numpy  (0) 2024.07.14
머신러닝에서의 Tensor란 무엇인가? Numpy, TensorFlow, Pytorch의 Tensor 알아보기  (0) 2024.07.13


'Machine Learning Math/Linear Algebra' 카테고리의 다른 글
  • Tensor 사칙 연산, 아다마르 곱셈(Hadamard Product) 한 번에 정리하기: Numpy, TensorFlow, PyTorch에서의 사용법 정리
  • 기저 벡터(Basis Vector)와 직교 벡터(Orthogonal Vector)
  • L2 Norm과 Unit Vector 알아보기 : Numpy, TensorFlow, PyTorch의 Norm 연산과 Unit Vector
  • 벡터 전치(Vector Transposition) 알아보기: Tensorflow, Pytorch, Numpy
심플코드
심플코드
프로그래밍을 어렵지 않게 풀어서 설명하는 기술 블로그
    반응형
  • 심플코드
    심플코드
    심플코드
  • 전체
    오늘
    어제
    • 분류 전체보기 (96)
      • 안드로이드를 위한 Coroutines (2)
      • Unit Testing (19)
      • GitHub Actions (0)
      • 공식 문서 번역 (35)
        • Coroutines 공식 문서 (35)
      • 알고리즘 (7)
        • Kotlin 자료구조 (0)
        • 알고리즘 (7)
        • Kotlin으로 구현하는 자료구조 (0)
      • 코딩 테스트 (0)
      • Deep Learning (0)
      • Machine Learning Math (17)
        • Linear Algebra (17)
      • ML (0)
      • Docker (15)
      • Kubernetes (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

    • 코틀린 코루틴의 정석 책 출간 소식
  • 인기 글

  • 태그

    unit testing
    도커
    Coroutines Channel
    junit
    unit test
    코루틴
    Machine Learning
    Kotlin
    pytorch
    Docker
    numpy
    코루틴 Flow
    Coroutines Context
    Coroutines Flow
    coroutine
    코루틴 채널
    컨테이너
    TensorFlow
    Coroutines
    mockito
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
심플코드
L1 Norm, L2 Norm, Squared L2 Norm, Infinity Norm 한 번에 정리하기 : Numpy, TensorFlow, PyTorch 에서 사용하기
상단으로

티스토리툴바