기본 연산

Python으로 시작하는 TensorFlow

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

TensorFlow 연산이란?

이미지는 TensorBoard로 그린 TensorFlow 그래프에서 연산과 텐서를 보여줍니다. 두 쌍의 행렬이 add 연산으로 결합되고, 결과 합이 곱해집니다.

Python으로 시작하는 TensorFlow

TensorFlow 연산이란?

이미지는 TensorBoard로 그린 TensorFlow 그래프에서 연산과 텐서를 보여줍니다. 하나의 add 연산이 표시됩니다.

Python으로 시작하는 TensorFlow

TensorFlow 연산이란?

이미지는 TensorBoard로 그린 TensorFlow 그래프에서 연산과 텐서를 보여줍니다. 두 개의 add 연산이 표시됩니다.

Python으로 시작하는 TensorFlow

TensorFlow 연산이란?

이미지는 TensorBoard로 그린 TensorFlow 그래프에서 연산과 텐서를 보여줍니다. 두 쌍의 행렬이 add 연산으로 결합되고, 결과 합이 곱해집니다.

Python으로 시작하는 TensorFlow

덧셈 연산자 적용

#Import constant and add from tensorflow
from tensorflow import constant, add

# Define 0-dimensional tensors
A0 = constant([1])
B0 = constant([2])
# Define 1-dimensional tensors
A1 = constant([1, 2])
B1 = constant([3, 4])
# Define 2-dimensional tensors
A2 = constant([[1, 2], [3, 4]])
B2 = constant([[5, 6], [7, 8]])
Python으로 시작하는 TensorFlow

덧셈 연산자 적용

# Perform tensor addition with add()
C0 = add(A0, B0)
C1 = add(A1, B1)
C2 = add(A2, B2)
Python으로 시작하는 TensorFlow

텐서 덧셈 수행하기

  • add()는 두 텐서의 원소별 덧셈을 수행합니다

  • 원소별 덧셈은 두 텐서의 형태가 같아야 합니다:

    • 스칼라 덧셈: $1+2=3$
    • 벡터 덧셈: $[1,2]+[3,4]=[4,6]$
    • 행렬 덧셈: $\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} + \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix} = \begin{bmatrix} 6 & 8 \\ 10 & 12 \end{bmatrix}$
  • add() 연산자는 오버로드되어 있습니다

Python으로 시작하는 TensorFlow

TensorFlow에서 곱셈 수행 방법

  • 원소별 곱셈multiply()로 수행합니다

    • 곱하는 텐서는 같은 형태여야 합니다
    • 예: [1,2,3]과 [3,4,5], 또는 [1,2]와 [3,4]
  • 행렬 곱셈matmul()로 수행합니다

    • matmul(A,B)는 A에 B를 곱합니다
    • A의 열 수 = B의 행 수여야 합니다
Python으로 시작하는 TensorFlow

곱셈 연산자 적용

# Import operators from tensorflow
from tensorflow import ones, matmul, multiply

# Define tensors
A0 = ones(1)
A31 = ones([3, 1])
A34 = ones([3, 4])
A43 = ones([4, 3])

  • 어떤 연산이 유효할까요?
    • multiply(A0, A0), multiply(A31, A31), multiply(A34, A34)
    • matmul(A43, A34)는 가능, matmul(A43, A43)는 불가
Python으로 시작하는 TensorFlow

텐서 차원 합계 구하기

  • reduce_sum()은 텐서의 차원에 따라 합을 구합니다
    • reduce_sum(A)는 A의 모든 차원을 합칩니다
    • reduce_sum(A, i)는 i차원으로 합칩니다
# Import operations from tensorflow
from tensorflow import ones, reduce_sum

# Define a 2x3x4 tensor of ones
A = ones([2, 3, 4])
Python으로 시작하는 TensorFlow

텐서 차원 합계 구하기

# Sum over all dimensions
B = reduce_sum(A)

# Sum over dimensions 0, 1, and 2
B0 = reduce_sum(A, 0)
B1 = reduce_sum(A, 1)
B2 = reduce_sum(A, 2)
Python으로 시작하는 TensorFlow

연습해 봅시다!

Python으로 시작하는 TensorFlow

Preparing Video For Download...