안녕하세요.
steemit 가입하고 첫 글 씁니다.
머신러닝과 주식 관련된 포스트를 올릴 생각입니다.
반갑습니다. 스팀잇 유저 여러분!
Tensorflow - MNIST
1. MNIST File Read
MNIST Data를 다운받아서 python에 불러온다. 일반적으로 머신러닝을 위해서 데이터를 구하고, 데이터를 나누고 (Training Data + Testing Data), 데이터를 Formatting 한다.
import tensorflow as tf
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
2. Hyper Parameter Setting
머신러닝을 하는데 있어서 필요한 Hyper Parameters를 정의한다. learning_rate는 learning을 하는 속도(가중치)값이라고 보면 된다. 값의 크기에 따라서 weights 값들이 얼마나 빠르게 update 되는지에 대한 값이다. 너무 클 경우에는 optimal solution을 뛰어넘어 learning이 제대로 안될 가능성이 있고, 너무 작을 경우에는 iteration을 과도하게 많이 필요하게 된다.
# Parameters
learning_rate = 0.001
training_iters = 200000
batch_size = 128
display_step = 10
Graph
텐서플로우는 데이터 플로우 그래프를 사용해서 수치 연산을 하는 라이브러리로 볼 수 있습니다. 그래프의 노드(node)는 수학적 연산을 나타내고 노드를 연결하는 그래프의 엣지(edge)는 다차원 데이터 배열(array)을 나타냅니다. 텐서플로우는 수치연산을 기호로 표현한 그래프 구조를 만들고 처리한다는 기본 아이디어를 바탕으로 구현되었습니다. 그래서 텐서플로우는 CPU, GPU의 장점을 모두 이용할 수 있고 안드로이드나 iOS 같은 모바일 플랫폼은 물론 맥 OS X와 같은 64비트 리눅스에서 바로 사용될 수 있습니다.
Tensor
A tensor is a multidimensional array
3.WX+b
MNIST 이미지는 28*28이기 떄문에 이를 1차원 배열로 나타내면 길이가 784인 배열로 나타낼 수 있다. 따라서 x변수의 크기를 float 타입으로 784로 잡는다. y는 output class의 크기로 숫자는 0부터 9까지 10가지의 수가 있기 때문에 크기를 float 타입으로 10로 잡는다.
# TF graph input
x = tf.placeholder("float", [None, 784]) # mnist data image of shape 28*28=784
y = tf.placeholder("float", [None, 10]) # 0-9 digits recognition => 10 classes
# Create a model
# Set model weights
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
with tf.name_scope("Wx_b") as scope:
# Construct a linear model
model = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax
# Add summary ops to collect data
# 추후 시각화를 위해 필요한 변수
w_h = tf.histogram_summary("weights", W)
b_h = tf.histogram_summary("biases", b)
placeholder
텐서플로우 파이썬 모듈을 임포트한 후 프로그램 실행 중에 값을 변경할 수 있는 placeholder라 부르는 심볼릭 변수 들을 정의합니다. 그리고 나서 텐서플로우에서 제공하는 곱셈 함수를 호출할 때 이 두 변수를 파라메타로 넘깁니다.
softmax function
Tensorflow scope
4. cost function
cost function을 이용해서 error가 최소가 되는 방향으로 learning 시킨다. 여기서는 cost function으로 popular하게 사용되는 'cross entropy'를 사용한다.
# More name scopes will clean up graph representation
with tf.name_scope("cost_function") as scope:
# Minimize error using cross entropy
# Cross entropy
cost_function = -tf.reduce_sum(y*tf.log(model))
# Create a summary to monitor the cost function
tf.scalar_summary("cost_function", cost_function)
7. training (Gradient Discent)
train은 cost_function을 Minimize하는 방향으로 learning되면 GradientDescent Algorithm 으로 learning_rate는 위에서 설정한 값을 이용하여 수행된다.
with tf.name_scope("train") as scope:
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost_function)
# Initializing the variables
init = tf.initialize_all_variables()
# Merge all summaries into a single operator
merged_summary_op = tf.merge_all_summaries()
8. 실제 수행 (Batch, Epoch 반복)
Epoch, Batch 순으로 반복되며, 위에서 정의한 optimizer를 실행시키고, avg_cost를 계산하여 display_step에 맞게 보여준다.
# Launch the graph
with tf.Session() as sess:
sess.run(init)
# Change this to a location on your computer
# 시각화를 위해 SummaryWriter를 설정해줌
summary_writer = tf.train.SummaryWriter('/LOCATION/ON/YOUR/COMPUTER/', graph_def=sess.graph_def)
# Training cycle
for iteration in range(training_iteration):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Fit training using batch data
sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
# Compute the average loss
avg_cost += sess.run(cost_function, feed_dict={x: batch_xs, y: batch_ys})/total_batch
# Write logs for each iteration
summary_str = sess.run(merged_summary_op, feed_dict={x: batch_xs, y: batch_ys})
summary_writer.add_summary(summary_str, iteration*total_batch + i)
# Display logs per iteration step
if iteration % display_step == 0:
print "Iteration:", '%04d' % (iteration + 1), "cost=", "{:.9f}".format(avg_cost)
print "Tuning completed!"
# Test the model
predictions = tf.equal(tf.argmax(model, 1), tf.argmax(y, 1))
# Calculate accuracy
accuracy = tf.reduce_mean(tf.cast(predictions, "float"))
print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})
Tensorflow의 주요 함수
| 함수 | 설명 |
|---|---|
| tf.add | 덧셈 |
| tf.sub | 뺄셈 |
| tf.mul | 곱셈 |
| tf.div | 나눗셈의 몫 |
| tf.mod | 나눗셈의 나머지 |
| tf.abs | 절대값을 리턴합니다. |
| tf.neg | 음수를 리턴합니다. |
| tf.sign | 부호를 리턴합니다.(역주: 음수는 -1, 양수는 1, 0 일땐 0을 리턴합니다) |
| tf.inv | 역수를 리턴합니다.(역주: 3의 역수는 1/3 입니다) |
| tf.square | 제곱을 계산합니다. |
| tf.round | 반올림 값을 리턴합니다. |
| tf.sqrt | 제곱근을 계산합니다. |
| tf.pow | 거듭제곱 값을 계산합니다. |
| tf.exp | 지수 값을 계산합니다. |
| tf.log | 로그 값을 계산합니다. |
| tf.maximum | 최대값을 리턴합니다. |
| tf.minimum | 최소값을 리턴합니다. |
| tf.cos | 코사인 함수 값을 계산합니다. |
| tf.sin | 사인 함수 값을 계산합니다. |
| tf.diag | 대각행렬을 리턴합니다. |
| tf.transpose | 전치행렬을 리턴합니다. |
| tf.matmul | 두 텐서를 행렬곱셈하여 결과 텐서를 리턴합니다. |
| tf.matrix_determinant | 정방행렬의 행렬식 값을 리턴합니다. |
| tf.matrix_inverse | 정방행렬의 역행렬을 리턴합니다. |