Tensor 사칙 연산, 아다마르 곱셈(Hadamard Product) 한 번에 정리하기: Numpy, TensorFlow, PyTorch에서의 사용법 정리

2024. 7. 18. 07:00·Machine Learning Math/Linear Algebra
반응형

Tensor의 연산

머신러닝을 하기 위해서는 Tensor에 대한 여러 연산을 수없이 해야 하기 때문에, Tensor의 기본 사칙연산과 아다마르 곱셈(hadamard product)을 이해하는 것은 중요하다. 이곳에서는 Tensor에서의 사칙 연산(더하기, 빼기, 곱하기, 나누기)에 대해 알아보고, 아다마르(Hadamard Product) 연산까지도 알아본다.

 

더하기 연산과 빼기 연산

Tensor는 기본적으로 더하기와 빼기 연산이 지원된다. 

더하기 연산은 다음과 같이 같은 위치의 원소를 더하는 방식으로 진행된다.

 

$\mathbf{a} + \mathbf{b} = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} + \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix} = \begin{bmatrix} 1+5 & 2+6 \\ 3+7 & 4+8 \end{bmatrix} = \begin{bmatrix} 6 & 8 \\ 10 & 12 \end{bmatrix}$

 

빼기 연산은 다음과 같이 같은 위치의 원소를 빼는 방식으로 진행된다.

 

$\mathbf{a} - \mathbf{b} = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} - \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix} = \begin{bmatrix} 1-5 & 2-6 \\ 3-7 & 4-8 \end{bmatrix} = \begin{bmatrix} -4 & -4 \\ -4 & -4 \end{bmatrix}$

 

곱하기 연산

곱하기 연산은 두가지이다. 한 가지는 내적(Dot Product)라 부르는 것이고, 다른 하나는 아다마르 곱셈이다.

 

아다마르 곱셈은 이전의 더하기, 빼기 연산과 마찬가지로 같은 위치의 원소를 곱하는 연산이다. 연산 기호는 $\circ$ 이다.

 

$\mathbf{a} \circ \mathbf{b} = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} \circ \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix} = \begin{bmatrix} 1 \cdot 5 & 2 \cdot 6 \\ 3 \cdot 7 & 4 \cdot 8 \end{bmatrix} = \begin{bmatrix} 5 & 12 \\ 21 & 32 \end{bmatrix}$

 

내적 연산은 우리가 흔히 아는 행렬에 대한 곱하기 연산이다. 연산 기호는 $\cdot$ 이다.

 

$\mathbf{a} \cdot \mathbf{b} = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} \cdot \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix} = \begin{bmatrix} 1 \cdot 5 + 2 \cdot 7 & 1 \cdot 6 + 2 \cdot 8 \\ 3 \cdot 5 + 4 \cdot 7 & 3 \cdot 6 + 4 \cdot 8 \end{bmatrix} = \begin{bmatrix} 19 & 22 \\ 43 & 50 \end{bmatrix}$

 

나누기 연산

나누기 연산은 같은 위치의 원소를 나누는 방식으로 진행된다. 

 

$\frac{\mathbf{a}}{\mathbf{b}} = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} \div \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix} = \begin{bmatrix} \frac{1}{5} & \frac{2}{6} \\ \frac{3}{7} & \frac{4}{8} \end{bmatrix} = \begin{bmatrix} 0.2 & \frac{1}{3} \\ \frac{3}{7} & 0.5 \end{bmatrix}$

 

Numpy에서의 연산

앞서 다룬 연산들을 Numpy를 사용해 하려면 다음과 같이 하면 된다.

import numpy as np

# 두 개의 Tensor 정의
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])

# 덧셈
add_result = np.add(a, b) # a + b로도 표현 가능

# 뺄셈
sub_result = np.subtract(a, b) # a - b로도 표현 가능

# 내적 (Dot 연산)
dot_product_result = np.dot(a, b) # a @ b로도 표현 가능
 
# 곱하기 (아다마르 연산)
mul_result = np.multiply(a, b) # a * b로도 표현 가능

# 나눗셈
div_result = np.divide(a, b) # a / b로도 표현 가능

print("Addition:\n", add_result)
print("Subtraction:\n", sub_result)
print("Dot Product:\n", dot_product_result)
print("Multiplication (Hadamard Product):\n", mul_result)
print("Division:\n", div_result)

 

그러면 다음과 같은 결과가 나온다.

Addition:
 [[ 6  8]
 [10 12]]
Subtraction:
 [[-4 -4]
 [-4 -4]]
Dot Product:
 [[19 22]
 [43 50]]
Multiplication (Hadamard Product):
 [[ 5 12]
 [21 32]]
Division:
 [[0.2        0.33333333]
 [0.42857143 0.5       ]]

 

TensorFlow에서의 연산

앞서 다룬 연산들을 TensorFlow를 사용해 하려면 다음과 같이 하면 된다.

import tensorflow as tf

# 두 개의 Tensor 정의
a = tf.constant([[1, 2], [3, 4]])
b = tf.constant([[5, 6], [7, 8]])

# 덧셈
add_result = tf.add(a, b) # a + b로도 표현 가능

# 뺄셈
sub_result = tf.subtract(a, b) # a - b로도 표현 가능

# 내적 (Dot 연산)
dot_product_result = tf.matmul(a, b) # a @ b로도 표현 가능

# 곱하기 (아다마르 연산)
mul_result = tf.multiply(a, b) # a * b로도 표현 가능

# 나눗셈 
div_result = tf.divide(a, b) # a / b로도 표현 가능

print("Addition:\n", add_result)
print("Subtraction:\n", sub_result)
print("Dot Product:\n", dot_product_result)
print("Multiplication (Hadamard Product):\n", mul_result)
print("Division:\n", div_result)

 

그러면 다음과 같은 결과가 나온다.

Addition:
 tf.Tensor(
[[ 6  8]
 [10 12]], shape=(2, 2), dtype=int32)
Subtraction:
 tf.Tensor(
[[-4 -4]
 [-4 -4]], shape=(2, 2), dtype=int32)
Dot Product:
 tf.Tensor(
[[19 22]
 [43 50]], shape=(2, 2), dtype=int32)
Multiplication (Hadamard Product):
 tf.Tensor(
[[ 5 12]
 [21 32]], shape=(2, 2), dtype=int32)
Division:
 tf.Tensor(
[[0.2        0.33333333]
 [0.42857143 0.5       ]], shape=(2, 2), dtype=float64)

 

 

PyTorch에서의 연산

앞서 다룬 연산들을 PyTorch를 사용해 하려면 다음과 같이 하면 된다.

import torch

# 두 개의 Tensor 정의
a = torch.tensor([[1, 2], [3, 4]])
b = torch.tensor([[5, 6], [7, 8]])

# 덧셈
add_result = torch.add(a, b) # a + b로도 표현 가능

# 뺄셈
sub_result = torch.subtract(a, b) # a - b로도 표현 가능 

# 곱셈(Dot 연산)
dot_product_result = torch.matmul(a, b) # a @ b로도 표현 가능

# 곱하기 (아다마르 연산)
mul_result = torch.multiply(a, b) # a * b로도 표현 가능

# 나눗셈
div_result = torch.divide(a, b) # a / b로도 표현 가능

print("Addition:\n", add_result)
print("Subtraction:\n", sub_result)
print("Dot Product:\n", dot_product_result)
print("Multiplication (Hadamard Product):\n", mul_result)
print("Division:\n", div_result)

 

그러면 다음과 같은 결과가 나온다.

Addition:
 tensor([[ 6,  8],
        [10, 12]])
Subtraction:
 tensor([[-4, -4],
        [-4, -4]])
Dot Product:
 tensor([[19, 22],
        [43, 50]])
Multiplication (Hadamard Product):
 tensor([[ 5, 12],
        [21, 32]])
Division:
 tensor([[0.2000, 0.3333],
        [0.4286, 0.5000]])

 

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

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

대칭 행렬(Symmetric Matrix)와 단위 행렬(Identity Matrix) 한 번에 정리하기: Numpy, TensorFlow, PyTorch 사용해 단위 행렬 만들기  (0) 2024.07.20
Frobenius Norm 이란 무엇인가? Numpy, TensorFlow, PyTorch에서의 Frobenius Norm 계산법 알아보기  (0) 2024.07.19
기저 벡터(Basis Vector)와 직교 벡터(Orthogonal Vector)  (1) 2024.07.17
L1 Norm, L2 Norm, Squared L2 Norm, Infinity Norm 한 번에 정리하기 : Numpy, TensorFlow, PyTorch 에서 사용하기  (0) 2024.07.16
L2 Norm과 Unit Vector 알아보기 : Numpy, TensorFlow, PyTorch의 Norm 연산과 Unit Vector  (0) 2024.07.15


'Machine Learning Math/Linear Algebra' 카테고리의 다른 글
  • 대칭 행렬(Symmetric Matrix)와 단위 행렬(Identity Matrix) 한 번에 정리하기: Numpy, TensorFlow, PyTorch 사용해 단위 행렬 만들기
  • Frobenius Norm 이란 무엇인가? Numpy, TensorFlow, PyTorch에서의 Frobenius Norm 계산법 알아보기
  • 기저 벡터(Basis Vector)와 직교 벡터(Orthogonal Vector)
  • L1 Norm, L2 Norm, Squared L2 Norm, Infinity Norm 한 번에 정리하기 : Numpy, TensorFlow, PyTorch 에서 사용하기
심플코드
심플코드
프로그래밍을 어렵지 않게 풀어서 설명하는 기술 블로그
    반응형
  • 심플코드
    심플코드
    심플코드
  • 전체
    오늘
    어제
    • 분류 전체보기 (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)
  • 블로그 메뉴

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

  • 공지사항

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

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
심플코드
Tensor 사칙 연산, 아다마르 곱셈(Hadamard Product) 한 번에 정리하기: Numpy, TensorFlow, PyTorch에서의 사용법 정리
상단으로

티스토리툴바