05-02 06:32
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[Artificial Intelligence / TensorFlow] R-TensorFlow 예제 - Basic Operation 본문

Artificial Intelligence/TensorFlow

[Artificial Intelligence / TensorFlow] R-TensorFlow 예제 - Basic Operation

cinema4dr12 2017. 4. 11. 14:09

by Geol Choi | 


지난 포스팅에 이어 R-TensorFlow 두번째 예제로 기본 오퍼레이션(Basic Operation)에 대하여 알아보도록 한다. 이번 예제는 TensorFlow의 중요한 기본 개념을 이해하는데 큰 도움이 되는 예제라고 생각이 드는 만큼 잘 이해하길 바란다.


TensorFlow 라이브러리 불러오기

TensorFlow 패키지가 현재 환경에 설치 되어있는지 확인하고 만약 설치되어 있지 않으면 설치하고, 해당 패키지 라이브러리를 로딩한다:


R CODE:

# import library if (! ("tensorflow" %in% rownames(installed.packages()))) { install.packages("tensorflow") } base::library(tensorflow)


constant 오퍼레이션 정의

다음과 같이 a, b 두 개의 변수를 Constant 오퍼레이션을 정의하는데, 이것은 단순히 오퍼레이션을 정의하는 것이지 실제로 어떠한 연산이 일어나는 것은 아니다.


R CODE:

# Basic constant operations # The value returned by the constructor represents the output of the Constant op. a <- tensorflow::tf$constant(2) b <- tensorflow::tf$constant(3)


위와 같이 정의된 Constant 오퍼레이션이 실제로 연산이 일어나도록 하려면 TensorFlow 세션을 시작하고 이 세션을 통해 연산이 일어나도록 해야함을 명심하기 바란다.


TensorFlow 세션 시작

다음의 코드를 통해 TensorFlow 세션을 시작한다:


R CODE:

# Start tf session sess <- tensorflow::tf$Session()


연산 결과 출력

a, b 두 개의 Constant 오퍼레이션에 대하여 덧셈 및 곱셈 연산을 TensorFlow 세션을 통해 수행하고 이들 결과를 출력하도록 한다:


R CODE:

# print arithmetic result base::print("a=2, b=3") res_1 <- base::sprintf("Addition with constants: %d", sess$run(a+b)) res_2 <- base::sprintf("Multiplication with constants: %d", sess$run(a*b)) base::print(res_1) base::print(res_2)


위의 코드에서 sprintf() 함수는 Formatted Text를 출력하기 위한 R의 CPP 표준함수이며, 코드 실행결과는 다음과 같다:

> base::print(res_1)
[1] "Addition with constants: 5"
> base::print(res_2)
[1] "Multiplication with constants: 6"


예상대로 2와 3의 덧셈과 곱셈은 각각 5와 6이 출력되었다.


placeholder를 통한 연산

placeholder는 TensorFlow의 매우 중요한 개념 중 하나인데, 이는 데이터 타입만 지정하고 실제 데이터는 실행 단계에서 입력받도록 하는 것이다. 그래서 placeholder의 입력 파라미터는 TensorFlow가 제공하는 데이터 타입인데, 그 유형은 다음 표에 정리하였다:


데이터 타입

설명

 bool

 boolean

 double

 64-bit double precision floating point (float64)

 float

 32-bit single precision floating point (float32)

 int32

 32-bit signed integer

 int64

 64-bit signed integer

 string

 sequence of bytes (바이트 시퀀스)

 uint8

 8-bit unsigned integer


다음과 같이, int16 데이터 타입으로 두 개의 placeholder를 정의하였다:


R CODE:

# Basic Operations with variable as graph input # The value returned by the constructor represents the output # of the Variable op. (define as input when running session) # tf Graph input a <- tensorflow::tf$placeholder(tensorflow::tf$int16) b <- tensorflow::tf$placeholder(tensorflow::tf$int16)


오퍼레이션 정의

TensorFlow에서의 오퍼레이션은 TensorFlow를 구성하는 중요한 기본 단위이며, 다른 프로그래밍 언어의 함수 개념과도 유사하다. 오퍼레이션이 정의되는 시점에서 실제로 실행되는 것이 아니라, TensorFlow 세션에서 이를 호출할 때 실제 연산이 수행된다. 앞서 언급하였던 constant 오퍼레이션도 세션으로부터 호출될 때 상수값이 지정되는 연산이 일어나는 것이다.

다음 코드에서 addmul이라는 두 개의 변수에 TensorFlow의 add()multiply() 연산을 정의하였다:


R CODE:

# Define some operations add <- tensorflow::tf$add(a, b) mul <- tensorflow::tf$multiply(a, b)


오퍼레이션 수행

오퍼레이션 수행을 위해 해당 오퍼레이션에 입력 변수를 공급해야 하는데 이에 대한 역할을 하는 것이 feed_dict이다. 즉, feed_dict를 통해 입력 변수 공급을 위해 Python Dictionary 형태로 변환하는 dict() 사용한다:


R CODE:

# Launch the default graph. # Run every operation with variable input res_3 <- base::sprintf("Addition with variables: %d", sess$run(add, feed_dict = dict(a = 2, b = 3))) res_4 <- base::sprintf("Multiplication with variables: %d", sess$run(mul, feed_dict = dict(a = 2, b = 3))) base::print(res_3) base::print(res_4)


Python-TensorFlow의 경우와는 달리, sess$run()의 feed_dict 입력변수 정의를 위해 dict()를 사용하고 있음을 기억해야 한다.

위의 코드를 실행한 결과는 다음과 같다:


> base::print(res_3)
[1] "Addition with variables: 5"
> base::print(res_4)
[1] "Multiplication with variables: 6"


행렬 연산

1-by-2 행렬과 2-by-1 행렬의 행렬곱 연산을 수행해 보자. 이를 위해 다음과 같이 두 개의 constant 오퍼레이션을 정의한다:


R CODE:

# The value returned by the constructor represents the output of the Constant op. matrix1 <- tensorflow::tf$constant(base::matrix(base::c(3.0, 3.0), nrow = 1, ncol = 2)) # Create another Constant that produces a 2x1 matrix. matrix2 <- tensorflow::tf$constant(base::matrix(base::c(2.0, 2.0), nrow = 2, ncol = 1))


즉,


\( matrix1 = \begin{bmatrix}3 & 3\end{bmatrix} \)


\( matrix2 = \begin{bmatrix}2\\2\end{bmatrix} \)


이다. 이 두 행렬의 곱셈을 하는 오퍼레이션을 위한 코드는 다음과 같다:


R CODE:

# Create a Matmul op that takes 'matrix1' and 'matrix2' as inputs. # The returned value, 'product', represents the result of the matrix # multiplication. product <- tensorflow::tf$matmul(matrix1, matrix2) # To run the matmul op we call the session 'run()' method, passing 'product' # which represents the output of the matmul op. This indicates to the call # that we want to get the output of the matmul op back. # # All inputs needed by the op are run automatically by the session. They # typically are run in parallel. # # The call 'run(product)' thus causes the execution of threes ops in the # graph: the two constants and matmul. # # The output of the op is returned in 'result' as a numpy `ndarray` object. result <- sess$run(product) matmul_result <- base::sprintf("Matrix Multiplication: %f", result) base::print(matmul_result)


matmul() 외에도 TensorFlow가 제공하는 행렬 오퍼레이션은 여러가지가 있는데 이 행렬 연산에 대한 내용은 이 곳을 참고하기 바란다.

위의 코드 실행 결과는 다음과 같다:


[1] "Matrix Multiplication: 12.000000"


다음 포스팅에서는 TensorFlow를 이용한 Linear Regression에 대하여 알아보도록 한다.


전체 소스 코드

마지막으로 본 포스팅에서 작성한 전체 R 소스 코드를 싣는다.


R-TensorFlow Code


Comments