TensorFlow란?
여러 노드로 이루어진 데이터 흐름 그래프를 이용하여 수적인 계산이 가능하도록 하는 파이썬 라이브러리다. 머신러닝 구현을 보다 편리하게 만들어주는 라이브러리로, 타 관련 라이브러리보다 자료도 많고 사용자도 많아 공부하기 좋은 환경이 갖추어져있다. 텐서플로우는 텐서가 노드들을 돌아다니며 만드는 흐름을 말한다. 즉, 그래프를 먼저 설계하고, 이에 대한 코딩을 진행해야하는 새로운 방식의 프로그래밍이 필요하다.
설치방법
- 텐서플로우를 다운받는다.
pip install tensorflow
- 텐서플로우-gpu를 다운받는다
pip install tensorflow-gpu
- 만약 다음과 같은 에러가 뜬다면 아래 코드를 통해 파이썬 버전이 3.5.4이고, 64bit가 맞는지 확인해보아야 한다.
Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow
import platform print(platform.architecture())
간단한 그래프 구성해보기
Hello World?
간단하게 Hello World
를 출력하는 텐서플로우 프로그램을 만들어보자.
import tensorflow as tf
hello = tf.constant("Hello World?")
sess = tf.Session()
print(sess.run(hello))
위와 같이 constant()
를 통해 노드를 생성할 수 있고, Session()
으로 세션을 생성해서 run()
으로 노드의 값을 출력해낼 수 있다.
계산 그래프
서로 다른 두 노드를 합을 가지는 노드로 연결되는 그래프를 만들어보자.
import tensorflow as tf
node1 = tf.constant(3.0, tf.float32)
node2 = tf.constant(4.0) # tf.float32로 암묵적으로 같다
node3 = tf.add(node1, node2)
sess = tf.Session()
print("row1 : ",sess.run(node3))
print("row2 : ",sess.run([node1, node2]))
위와같이 constant로 노드의 값과 자료형을 지정해줄 수 있고, add()
를 통해 두 노드를 합할 수 있다. 역시 세션을 만들고 run할 수 있다.
지금까지는 노드를 만들면서 동시에 값을 넣어주었다. 이번에는 노드를 먼저 만들고 나중에 값을 넣는 그래프를 만들어보자.
import tensorflow as tf
node1 = tf.placeholder(tf.float32)
node2 = tf.placeholder(tf.float32)
node3 = node1 + node2
sess = tf.Session()
print("node1 = 3, node2 = 4.5 일 때, node3 = ",
sess.run(node3, feed_dict={node1:3,node2:4.5}))
print("node1 = [1,3], node2 = [2,4] 일 때, node3 = ",
sess.run(node3, feed_dict={node1:[1,3],node2:[2,4]}))
위와 같이 placeholder()
를 통해 값이 없는 노드를 생성해주고, 세션을 만든 후에 run할 때, 값을 전달해주어 관계에 따라 노드가 완성될 수 있도록 그래프를 만들 수 있다.
기본 문법
Ranks(차수)
해당 그래프가 몇차원인지를 나타내는 방법이다.
Rank | Math entity | Python example |
---|---|---|
0 | Scalar | s=483 |
1 | Vector | v=[1,2,3] |
2 | Matrix | m=[[1,2,3],[4,5,6],[7,8,9]] |
3 | 3-Tensor | t=[ [[1],[2]], [[3],[4]], [[5],[6]] ] |
n | n-Tensor | … |
위의 표에서 알 수 있듯이 3차부터는 n-Tensor
라고 부른다.
Ranks(요소 개수)
해당 차수에 몇개씩 있는지를 나타내는 방법이다. |Rank|Shape|Dimension number|Example| |:-:|:-:|:-:|:-:| |0|[]|0-D|0-D 텐서. 스칼라.| |1|[D0]|1-D|1-D 텐서.| |2|[D0, D1]|2-D|2-D 텐서.| |3|[D0, D1, D2]|3-D|3-D 텐서.| |n|[D0,…,Dn-1]|n-D|n-D 텐서.|
위와 같이 각 차원(Dn)에 몇개의 요소가 존재하는지 리스트 형태로 나타낼 수 있다(Shape).
Data Types
텐서플로우에서 사용할 수 있는 자료형들이 있다. 주로 tf.float32
가 가장 많이 쓰인다고 한다.
|Data type|Python type|
|:-:|:-:|
|DT_FLOAT|tf.float32|
|DT_DOUBLE|tf.float64|
|DT_INT8|tf.int8|
|DT_INT16|tf.int16|
|DT_INT32|tf.int32|
|DT_INT64|tf.int64|
|…|…|
텐서플로우를 통한 데이터셋 기반 그래프 구축
``` python x_set = [1,2,3] y_set = [10,20,30]
Rank가 1인(1차원) 랜덤한 값을 tf가 사용할 변수로 선언해준다.
W = tf.Variable(tf.random_normal([1]), name=’weight’) b = tf.Variable(tf.random_normal([1]), name=’bias’)
Wx+b
hypothesis = x_set * W + b
cost
cost = tf.reduce_mean(tf.square(hypothesis - y_set))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01) train = optimizer.minimize(cost)
sess = tf.Session() sess.run(tf.global_variables_initializer)