가. Variables
[잘못된 사용의 예]
# CASE1
# 아래처럼은 동작하지 않음, 왜 냐면 Tensor 연산은 Session 위에서 이루어져야 하기 때문
try :
# 일반적인 변수처럼 처리하려고 하면 발생한느 현상
x = tf.constant(35, name='x')
y = tf.Variable(x + 5, name='y')
#<tensorflow.python.ops.variables.Variable object at 0x7fabe98cced0>
print(y)
except:
print("ERROR-1")
[잘 사용한 예]
# CASE2
# 아래처럼 실행하면 40이 리턴됨
try :
x = tf.constant([35, 40, 45], name='x')
y = tf.Variable(x + 5, name='y')
# 지금까지 정의한 변수를 Session 에서 사용할 수 있도록 초기화 합니다
model = tf.initialize_all_variables()
# with Session as 구분 사용시 Session 종료는 자동
with tf.Session() as session:
session.run(model)
print(session.run(y))
except:
print("ERROR-2")
[Numpy 를 사용하여 사이즈간 큰 데이터 생성 및 처리 테스트]
# CASE3
# numpy 를 사용해서 사이즈가 큰 데이터를 생성하고 식을 조금 복잡하게 수행
try:
data = np.random.randint(1000, size=10000)
x = tf.constant(data, name='x')
y = tf.Variable(x**2 + 5*x + 5, name='y')
model = tf.initialize_all_variables()
with tf.Session() as session:
session.run(model)
print(session.run(y))
except:
print("ERROR-3")
[루프 연산]
# CASE4
# for i in range(5): 을 사용한 루프 연산
try:
x = tf.Variable(0, name='x')
model = tf.initialize_all_variables()
with tf.Session() as session:
for i in range(5):
session.run(model)
x = x + 1
print(session.run(x))
except:
print("ERROR-4")
[TensorBoard 연동]
TensorBoard는 별도의 실행이 필요한 Tool 로써 아래와 같이 사용하면 됨
# 실행 방법 : tensorboard --logdir=/tmp/basic # http://localhost:6006
[분석 파일 생성 ]
# CASE5
# TensorBoard 를 활용한 그래프 출력
try:
data = np.random.randint(1000, size=10000)
x = tf.constant(data, name='x')
y = tf.Variable(x**2 + 5*x + 5, name='y')
with tf.Session() as session:
merged = tf.merge_all_summaries()
writer = tf.train.SummaryWriter("/tmp/basic", session.graph)
model = tf.initialize_all_variables()
session.run(model)
print(session.run(y))
# 실행 방법 : tensorboard --logdir=/tmp/basic
# http://localhost:6006
except:
print("ERROR-5")
나. Array
[이미지 로딩]
# -*- coding: utf-8 -*-
import os
import tensorflow as tf
import matplotlib.image as mpimg
# 이미지를 로딩한다
filename = os.path.dirname(__file__) + "/MarshOrchid.jpg"
image = mpimg.imread(filename)
height, width, depth = image.shape
# 이미지의 메트릭스 형태 출력
print("1. Initial : height :{0} , width :{1} , depth :{2}".format(height, width, depth))
[축을 변경]
perm 에서 데이터 순서대로 축의 순서를 의미하며, 입력하는 숫자가 바꾸고 싶은 축의
변호가 된다. 아래의 예는 2 번 축과 3 번 축을 서로 바꾸겠다라는 의미가 된다
tf.transpose(x, perm=[0, 2, 1])
# 축을 변경한다
try:
x = tf.Variable(image, name='x')
model = tf.initialize_all_variables()
with tf.Session() as session:
# Array 위치가 축 (x,y,z), 거기에 입력하는 숫자가 바꾸고 싶은 차원
x = tf.transpose(x, perm=[0, 2, 1])
#x = tf.transpose(x, perm=[0 ,1, 2])
session.run(model)
result = session.run(x)
height, width, depth = result.shape
print("2. Transpose : height :{0} , width :{1} , depth :{2}".format(height, width, depth))
except Exception as err:
print(err)
[데이터 순서 정렬]
뭔가 약간 잘 이해가 안가는 부분이 있는데 우선 아래 처럼 사용하면 X 축 데이터에 대해
역순으로 재 정렬하게 된다.
# 배열의 순서를 변경한다
try:
#보기 좋게 데이터를 축소해보자
tem_len = 2
temp_img = image[0:tem_len][0:tem_len]
x = tf.Variable(temp_img, name='x')
model = tf.initialize_all_variables()
#변경전 데이터 출력
for i in range(tem_len):
for j in range(tem_len):
print("Before :[{0},{1}] : {2}".format(i, j, temp_img[i][j]))
#다른 메서드들 : https://www.tensorflow.org/versions/r0.10/api_docs/python/array_ops.html
#x는 인풋 데이터
#데이터 사이즈 [width] * height = [5, 5, 5, 5, 5] 생성
# seq_dim 1 : 데이터의 순서가 역순으로 정렬 됨
# seq_dim 2 : 데이터 안의 내용이 역순 정렬
#seq_dim 3 : seq_dim must be < input.dims() (3 vs 3)
#batch_dim = 0 위에서 아래로 연산 수행
with tf.Session() as session:
x = tf.reverse_sequence(x, [tem_len] * tem_len, 2, batch_dim=0)
session.run(model)
result = session.run(x)
#변경후 데이터 출력
for i in range(tem_len):
for j in range(tem_len):
print("After :[{0},{1}] : {2}".format(i, j, result[i][j]))
except Exception as err:
print(err)
다. PlaceHolder
아래는 PlaceHolder 를 설명하는 예제이다 . PlaceHolder 란 값은 미정인데, 어떤 타입, 데이터 구조를 갖는 데이터를 정의하겠다라는 말이다.
아래는 어떤 데이터인지는 모르겠지만, float 타입으로 사이즈가 3인 데이터를 정의하겠다라는 것이다. 만약 데이터의 수도 정의할 수 없다면 None 을 정의해주면 된다.
x1 = tf.placeholder("float", 3)
x2 = tf.placeholder("float", None)
이렇게 정의한 데이터는 아래와 같이 실제 데이터를 맵핑할 수 있다
with tf.Session() as session:
result = session.run(y, feed_dict={x1: [1, 2, 3], x2: [1, 2, 3], x3: [1, 2, 3] })
[전체 코드]
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
# 데이터 타입, 사이즈 정의 ,None은 무한대
x1 = tf.placeholder("float", 3)
x2 = tf.placeholder("float", None)
x3 = tf.placeholder("float", 3)
y = x1 * 2 + x2 + x3
# 데이터의 형태는 아래와 같이 이중 배열로로 정의 가능
x4 = tf.placeholder("float", [None, 3])
y2 = x4 + 1
# 기본적으로 연산하려면 세션에서 해야됨
with tf.Session() as session:
# 데이터 직접 삽입
result = session.run(y, feed_dict={x1: [1, 2, 3], x2: [1, 2, 3], x3: [1, 2, 3] })
print(result)
# 데이터 직접 삽입
x_data = [[1, 2, 3], [4, 5, 6], ]
result2 = session.run(y2, feed_dict={x4: x_data})
print(result2)
# 이미지와 동일하게 가로, 세로, RGB 처럼 표현하는 테스트 데이터를 만들어 보자
data1 = np.random.randint(10) # 이미지로 치면 빨간색
data2 = np.random.randint(10) # 초록색
data3 = np.random.randint(10) # 파란색
# 이미지로 치면 3색 표현 , 가로 5, 세로 5 인 이미지가 되겠다
raw_image_data = [[[data1, data2, data3]] * 5 ] * 5
# 데이터! 출력
print("1. Original : {0}".format(raw_image_data))
# 홀더를 만든다 이홀더는 가로 세로 사이즈 제한은 없고 색은 3가지 RGB 로 표현
# 하는 모든 데이터를 커버 할 수 있다
image = tf.placeholder("uint8", [None, None, 3])
# 메트릭스를 자른다, 첫번째는 소스 메트릭스, 두번재는 시작 주소, 세번째는 끝 메트릭스
# 시작과 끝 사이의 데이터만 리턴한다, -1은 데이터 최대 길이라는 이야기다
slice = tf.slice(image, [0, 0, 0], [-1, 1, -1])
# 슬라이스를 연산한다
with tf.Session() as session:
result = session.run(slice, feed_dict={image: raw_image_data})
# 슬라이스 연산후 데이터
print("2. Transformed : {0}".format(result))
[결과]
/root/anaconda2/bin/python /root/PycharmProjects/TensorLearn/chap3_placeholder.py [ 4. 8. 12.] [[ 2. 3. 4.] [ 5. 6. 7.]] 1. Original : [[[3, 5, 9], [3, 5, 9], [3, 5, 9], [3, 5, 9], [3, 5, 9]], [[3, 5, 9], [3, 5, 9], [3, 5, 9], [3, 5, 9], [3, 5, 9]], [[3, 5, 9], [3, 5, 9], [3, 5, 9], [3, 5, 9], [3, 5, 9]], [[3, 5, 9], [3, 5, 9], [3, 5, 9], [3, 5, 9], [3, 5, 9]], [[3, 5, 9], [3, 5, 9], [3, 5, 9], [3, 5, 9], [3, 5, 9]]] 2. Transformed : [[[3 5 9]] [[3 5 9]] [[3 5 9]] [[3 5 9]] [[3 5 9]]]
라. Interactive Session
[기존 방식]
# CASE 1 : with session syntax
# 아래와 같이 사용시 자동으로 세션이 종료됨, 단 Sessin.run 을 일일히 실행 필요
try:
x = tf.constant(data, name='x')
y = tf.Variable(x**2 + 5*x + 5, name='y')
model = tf.initialize_all_variables()
with tf.Session() as session:
session.run(model)
print(session.run(y))
except:
print("ERROR-1")
[interactive 방식]
# CASE 2 : InteractiveSession
# 매번 session.run 을 할 필요가 없음, 단 마지막에 session.close() 필수
try:
session = tf.InteractiveSession()
x = tf.constant(data, name='x')
y = x ** 2 + 5 * x + 5
print(y.eval())
session.close()
except:
print("ERROR-2")