Tensorflow - MNIST

in #kr7 years ago (edited)

안녕하세요.
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정방행렬의 역행렬을 리턴합니다.

참고 사이트

김성훈 교수님 강의 정리

Sort:  

스팀잇에 오신것 을 환영합니다.^^
저는 krwhale이라는 아기고래와 코인시세 챗봇을 운영하고 있어요 :)
- 아기고래에게 Voting 받는 법
- 코인시세 챗봇
1주일 뒤 부터 유용하게 쓰실 수 있을 거에요~^^

Nice to meet you, @koreamin! Welcome to the Steemit Community, wish you good luck and a good start, ive send you a small tip and followed you, hope you have an amazing day! :)

nice to meet you, thankyou! :)

반갑습니다. 환영합니다.

Congratulations @koreamin! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

안녕하세요. 스팀잇 가입하신 것을 진심으로 환영합니다.
KR 일일 Top10 랭크 순위 랭킹, 댓글왕, 보팅왕, 고래왕, 큐레이터 정보 등 kr커뮤니티를 한눈에 볼 수 있습니다.
kr, kr-newbie, kr-join(가입인사시)을 태그에 넣으면 좀 더 많은 분들이 포스팅을 볼 수 있습니다.
'kr' 태그의 순서를 맨앞으로 넣어야 kr 카테고리가 됩니다.

감사합니다!

스팀잇 사용에 있어서 필요한 사항을 링크하였습니다. 도움이 되길 바랍니다.


요즘은 적절한 태그 사용에 따라 포스팅 노출 횟수가 달려있다고 해도 과언이 아닙니다.

뉴비시라면 기본적으로 포스팅하실때 태그에 kr과 kr-newbie 는 달아주시고

오랜만에 일주일 간 kr 관련 태그에 올라온 포스팅 수를 뽑아봤습니다.

이 포스팅을 참조하여 적절한 태그를 넣어주세요. 그래야 사람들에게 노출이 될 확률이 높습니다. 꼭 글많은 태그가 노출이 많은건 아니지만 그래도 적절한 태그사용은 도움이 됩니다. (kr-join 은 맨 처음 가입시 한번만 사용해주시는게 좋습니다.강제는 아니지만 태그위주로 분류되는 요즘은 자기소개도 아닌데 조인 태그를 계속 사용하면 아마 사람들이 싫어할수도 있으니까요. )


어떤 주제에 대한 의견 내시는걸 좋아하신다면 https://steemit.com/created/kr-agora
이곳에 들어가셔서 주제를 확인후 다양한 사람들의 의견을 참조하여 댓글및 kr-agora 태그로 의견을 포스팅하시고 사람들과 소통하시면 좀더 재미있게 즐기실수 있습니다.

글을 쓰고 나면 보상이 일주일 뒤에 들어오다보니 그때까지는 스팀달러가 없는경우가 대부분입니다.
살짝 느껴보시라고 2달라 보내드립니다.


1달러는
스팀달러를 전송해보자

위 링크를 참고해서 girina79 님께 1달라를 보내보세요. 현재 보육원 아이들을 후원하고 계십니다 .
세 명의 아이를 후원합니다. 보팅으로 지원해 주세요 !!!!!


다른 1달라는
스팀달러를 스팀파워로 바꿔보자
이걸 따라해 보세요. 어느정도 사용법을 익히기 위해 소액으로 미리 해보시는것이 좋습니다.

반갑습니다.
환영합니다. ^^

오!! 텐서 플로우!!
머신러닝을 접목한..
뭔가 굉장히 복잡해 보이지만 엄청 있어 보여요!!
환영합니다!! ㅎㅎ

Coin Marketplace

STEEM 0.18
TRX 0.16
JST 0.029
BTC 63566.44
ETH 2483.51
USDT 1.00
SBD 2.67