블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

Tensorflow Manipulation 강좌를 정리한다.





Array


- rank, shape, axis을 array로 나타냄.

- [-1] array의 마지막 item

- t[2:5] index 3부터 5까지 items

- t[:2] 처음부터 index 2까지 

- t[3:] index 3에서 끝까지 


[1,2,3] rank(1), shape(3)

[[1,2],[3,4]] rank(2), shape(2,2)


axis=0 가장 바깥쪽, axis=-1 가장 안쪽을 표현하고 axis을 통해 shape을 이동한다. 







Matrix Manipulation


matmul


matrix 곱은 반드시 matmul을 사용한다. 

- tf.matmul((2,2) , (2,1)) => (2,1)




broadcasting


matrix끼리 shape이 다르더라도 matrix끼리 연산을 가능토록 shape을 자동으로 맞춰준다. 잘 알고 사용하면 좋지만 조심해라. 



reduce_mean 


(평균) 호출시 입력값들의 type에 주의한다.


axis를 0 이냐 1 이냐에 따라 다른다.

>>> import tensorflow as tf

>>> sess = tf.Session()

>>> sess.run(tf.global_variables_initializer())

>>> x = [[1.,2.],[3.,4.]]

>>> tf.reduce_mean(x).eval(session=sess)

2.5


>>> tf.reduce_mean(x, axis=1).eval(session=sess)

array([1.5, 3.5], dtype=float32)



reduce_sum 


axis=-1  제일 안쪽값을 합치고 이에 대한 평균을 낸다. 



argmax


큰값이 있는 위치 index를 구하는 것이다. 



reshape


주로 (...., z) 가장 안쪽에 있는 z 값은 그대로 가져가고, 앞의 것을 reshape한다.



reshape 하나의 형태 sqeeze는 펴주는 역할, expand_dims 차원을 더 추가할 경우 




One Hot 


가장 큰 값이 있는 곳을 1로 하고 나머지는 0으로 바꿈. One hot을 하면 dimension (rank)가 하나 더 생기므로 다시 reshape을 한다. 

마지막 3만 남기고 나머지는 차원 1로 만들어주는 것 



Casting


타입 바꿔주기 



Stack


쌓기를 만들어줌. 주어진 데이터들에서 axis와 stack을 이용해 새로운 matrix를 만듦



Ones and Zeros like


가지고 있는 shape과 똑같은 0 또는 1로 채워진 shape을 만들때 사용



Zip


복수의 tensor를 한방에 처리하기 





참조


- 김성훈교수님의 Tensorflow Manipulation 강좌

- reduce_sum reduce_mean 사용법

posted by 윤영식

딥러닝 개념 강좌를 정리한다.





History


X Input을 가중치 W로 곱한후 모두 합한 다음 bias(b)를 더하고 activation function을 통할 때 1 또는 0으로 나온다. 1이면 수행하고 0이면 수행하지 않는다. 



XOR 문제. Linear하게 선을 그어도 심플한 모델을 가지고도 값을 구하지 못함. AND, OR는 단순하지만





1969 민스키 교수의 저서에서 XOR 문제해결을 위해 MultiLayer로 만들면 해결되지만 여기서 중간의 W, b를 학습할 수 없다이야기 함. 이에 대해 대부분 설득당 함.  




1986년 힌튼(Hinton)이 Back Propagation 알고리즘을 통해 error를 만날때 다시 뒤로 보내서 W,b를 구하자




Convolutional Neural Networks (CNN)


라쿤(LeCun) 교수는 다른 방법으로 접근. 그림을 볼 때 일부만 활성화 되고 부분마다 하는 역할이 틀리고 이들이 합쳐져서 판단하게 된다. 


부분부분을 예측하고 각각을 합쳐서 최종 판단한다. 

예) 자율주행차, 알파고



Backpropagation Big Problem


1990년대 Layer가 많아서 뒤로 갈 수록 제대로 전달되지 않는다. neural network보다 SVM, RandomForest같은 다른 알고리즘이 더 잘 동작함을 알게됨. 

다시 금 침체기에 들어간다. 




CIFAR(캐나다) 단체


CIFAR 에서 일하면 불씨를 이어감. 2006, 2007년 두개의 논문이 나옴.

- layer마다 초기값을 잘 주면 실행 가능하다

- 신경망을 구축하면 복잡한 문제를 해결할 수 있다. 

이때 Neural Network을 Deep Learning이라고 바꿈.




Hinton의 Alex박사가 ImageNet (이미지학습) 의 오류가 26% -> 15%로 떨어짐. 2015년에는 3%의 에러로 떨어졌다. (using Convolutional Neural Network)

요즘) Deep API, 알파고, 유튜브의 번역글, 페이스북의 피드, 구글검색엔진의 결과, 넷플릭스의 추천시스템, 아마존의 상품 추천시스템



잘 안되었던 4가지 상황



뒤 강좌에서 4가지 문제에 대해 알아본다.



지금 해야하는 이유






참조


- 김성훈교수님의 딥러닝 개념 강좌

- 김성훈교수님의 딥러닝 XOR 강좌

posted by 윤영식

Training/Test Set  강좌를 정리한다.




Training and test set


훈련시킬 데이터와 테스트 데이터를 나누어서 예측을 검증해 보아야 한다. 



Training set로 모델을 만들고 Validation set으로 모의 시험을 한다. 이후 Testing set으로 모델을 최종 테스트한다. 


테스트 데이터는 모델 입장에서 한번도 보지 않는 데이터가 된다. 






Big data set


Training set이 많을 경우. 몇개의 그룹으로 짤라서 학습을 시킨다. 이것을 Online Learning이라 부른다.

- image: training set

- label: Y 결과값이 있는 test set



데이터 사이즈 부르기 


- 전체 데이터를 한번 학습 시킨 것 = epoch (에포크)

- 몇개씩 짤라서 학습 = batch size

- epoch/batch size = iteration size 




Training Set으로 모델 만들기 예제





Testing Set으로 테스트하기 


- sess.run 또는 accuracy.eval 동일하다






참조


- 김성훈교수님의 Training/Testing 강좌

- Github MNIST data 예제



posted by 윤영식

ML Tips 강좌를 정리한다.




Learning rate 정하기


경사를 따라 내려가는 정도를 Learning rate이라 한다. 학습rate을 잘 정하는 것이 중요하다. 

- learning rate을 큰값을 사용할 때 밖으로 튕겨 나갈 때(overshooting) 잘 못된 값이다.

  


- learning rate이 작은값이면 step이 작아서 멈춰버릴 수 있다. 

   


해결 주로 초기에 0.01 으로 시작하고 작게 또는 크게 적용해 본다.




Big Learning rate


5 스텝에서 값이 무한대로 가버린다.



Small Learning rate


198 스텝이 되어도 cost의 값이 작지 않다면 의심해 봐야 한다. 




Data (X) preprocessing


Weight이 여러개 일때 2차원으로 표시할 경우 경사면을 따라서 낮은 지점에 내려가는 것이 목적이다. 데이터간 큰 차이가 있을 때 노말라이즈(Normalize)를 수행한다. 

- 0에 수렴되게 하거나

- 특정 범위안에 놓이게 하거나

학습이 제대로 이루어지지 않고 있다면 데이터중에 차이가 큰값이 있을 수 있다. 이를 제거하기 위해 Normalize를 한다. 



Learning rate도 적절한데 결과에 NaN이 있거나 이상하다면 Normalize 안된 Input값을 의심해 본다. w1, w2의 그래프를 보면 길게 늘어져 있으면 None Normalize이다.



해결하는 방법: MixMaxScaler(xy)를 사용한다.


예제 일부 코드

import tensorflow as tf

import numpy as np

tf.set_random_seed(777)  # for reproducibility



def MinMaxScaler(data):

    numerator = data - np.min(data, 0)

    denominator = np.max(data, 0) - np.min(data, 0)

    # noise term prevents the zero division

    return numerator / (denominator + 1e-7)



xy = np.array([[828.659973, 833.450012, 908100, 828.349976, 831.659973],

               [823.02002, 828.070007, 1828100, 821.655029, 828.070007],

               [819.929993, 824.400024, 1438100, 818.97998, 824.159973],

               [816, 820.958984, 1008100, 815.48999, 819.23999],

               [819.359985, 823, 1188100, 818.469971, 818.97998],

               [819, 823, 1198100, 816, 820.450012],

               [811.700012, 815.25, 1098100, 809.780029, 813.669983],

               [809.51001, 816.659973, 1398100, 804.539978, 809.559998]])


# very important. It does not work without it.

xy = MinMaxScaler(xy)

print(xy)


x_data = xy[:, 0:-1]

y_data = xy[:, [-1]]






Overfitting


학습데이터가 실제에 잘 맞지 않을 경우. 

- model은 일반적으로 적용가능하다 (regularization: 일반화)

- model2는 Overfitting으로 주어진 데이터에 specification되어 있다. => 특정 데이터에 맞춰서 선이 구부러져 있을 때 



Cost function에 Regularization(일반화)를 해준다. 선이 구부러진다는 것은 값이 커지는 것이므로 이를  조절 한다. 

Cost function = 기존 cost function + (람다*합W2)


람다: regularization strength





참조


- 김성훈교수님의 ML Tips 강좌

- 김성훈교수님의 Tips 실습 강좌

posted by 윤영식

Multinomial Classification에 사용하는 Softmax Classification을 Tensorflow로 구현하는 강좌를 정리한다.




Softmax Function


0.7 + 0.2 + 0.1 확률(Probabilities)값을 더하면 1이 된다. 






Cost Function


Loss function 구현하고 minize cost로 GradientDescentOptimizer를 사용한다. 




Tensorflow 실습


One-Hot Encoding은 하나의 자리만 1을 갖는다. 예) y_data

import tensorflow as tf

tf.set_random_seed(777)  # for reproducibility


x_data = [[1, 2, 1, 1],

          [2, 1, 3, 2],

          [3, 1, 3, 4],

          [4, 1, 5, 5],

          [1, 7, 5, 5],

          [1, 2, 5, 6],

          [1, 6, 6, 6],

          [1, 7, 7, 7]]

y_data = [[0, 0, 1],

          [0, 0, 1],

          [0, 0, 1],

          [0, 1, 0],

          [0, 1, 0],

          [0, 1, 0],

          [1, 0, 0],

          [1, 0, 0]]


X = tf.placeholder("float", [None, 4])

Y = tf.placeholder("float", [None, 3])

nb_classes = 3  #클래스의 갯수


# Shape

# 4 = X값, nb_classes 출력값

W = tf.Variable(tf.random_normal([4, nb_classes]), name='weight')

b = tf.Variable(tf.random_normal([nb_classes]), name='bias')


# tf.nn.softmax computes softmax activations

# softmax = exp(logits) / reduce_sum(exp(logits), dim)

hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)


# Cross entropy cost/loss

cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1))

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)


# Launch graph

with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())


    #Hypothesis에 대해 학습하여 최적의 W,b를 구함

    for step in range(2001):

        sess.run(optimizer, feed_dict={X: x_data, Y: y_data})

        if step % 200 == 0:

            print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}))


    print('--------------')


    # Testing & One-hot encoding: 예측을 하게 한다. argmax에서 최강자를 골라준다.


    a = sess.run(hypothesis, feed_dict={X: [[1, 11, 7, 9]]})

    print(a, sess.run(tf.argmax(a, 1)))


    print('--------------')


    b = sess.run(hypothesis, feed_dict={X: [[1, 3, 4, 3]]})

    print(b, sess.run(tf.argmax(b, 1)))


    print('--------------')


    c = sess.run(hypothesis, feed_dict={X: [[1, 1, 0, 1]]})

    print(c, sess.run(tf.argmax(c, 1)))


    print('--------------')


    all = sess.run(hypothesis, feed_dict={X: [[1, 11, 7, 9], [1, 3, 4, 3], [1, 1, 0, 1]]})

    print(all, sess.run(tf.argmax(all, 1)))



==> 결과 1 0 2

[[1.3890432e-03 9.9860197e-01 9.0612402e-06]

 [9.3119204e-01 6.2902056e-02 5.9058843e-03]

 [1.2732767e-08 3.3411323e-04 9.9966586e-01]] [1 0 2]






Fancy Softmax Classifier


cross_entropy, reshape, one-shot encoding을 사용하여 좀 더 Fancy하게 Softmax Classifier를 만든다. 

- score(logit)을 구함 => softmax function을 거치면 확률값이 나옴. 식: hypothesis  tf.nn.softmax(tf.matmul(X,W))


- hypothesis를 Cross entropy cost/Loss 를 만듦. 1)번 수식을 2)번 수식처럼 단순화함. Logits을 사용함.



동물원 예제

- 6가지 종류의 동물이 있다. 이것을 one hot을 이용해 가설을 학습시킨다. 

- tf.one_hot(...)을 호출하면 한차원 더 생기고 이것을 원위치 시키려면 tf.reshape(...)을 호출한다. 


import tensorflow as tf

import numpy as np

tf.set_random_seed(777)  # for reproducibility


# Predicting animal type based on various features

xy = np.loadtxt('data-04-zoo.csv', delimiter=',', dtype=np.float32)

x_data = xy[:, 0:-1]

y_data = xy[:, [-1]]


print(x_data.shape, y_data.shape)


nb_classes = 7  # 0 ~ 6


X = tf.placeholder(tf.float32, [None, 16])

Y = tf.placeholder(tf.int32, [None, 1])  # 0 ~ 6

Y_one_hot = tf.one_hot(Y, nb_classes)  # one hot

print("one_hot", Y_one_hot)

Y_one_hot = tf.reshape(Y_one_hot, [-1, nb_classes])

print("reshape", Y_one_hot)


W = tf.Variable(tf.random_normal([16, nb_classes]), name='weight')

b = tf.Variable(tf.random_normal([nb_classes]), name='bias')


# tf.nn.softmax computes softmax activations

# softmax = exp(logits) / reduce_sum(exp(logits), dim)

logits = tf.matmul(X, W) + b

hypothesis = tf.nn.softmax(logits)


# Cross entropy cost/loss

cost_i = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y_one_hot)

cost = tf.reduce_mean(cost_i)

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)


# 정확도를 구한다. 

prediction = tf.argmax(hypothesis, 1)

correct_prediction = tf.equal(prediction, tf.argmax(Y_one_hot, 1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# Launch graph

with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())


    # 학습을 수행한다

    for step in range(2000):

        sess.run(optimizer, feed_dict={X: x_data, Y: y_data})

        if step % 100 == 0:

            loss, acc = sess.run([cost, accuracy], feed_dict={X: x_data, Y: y_data})

            print("Step: {:5}\tLoss: {:.3f}\tAcc: {:.2%}".format(

                step, loss, acc))


    # Let's see if we can predict: 잘 예측되는지 확인한다. 

    pred = sess.run(prediction, feed_dict={X: x_data})

    # y_data: (N,1) = flatten => (N, ) matches pred.shape

    for p, y in zip(pred, y_data.flatten()):

        print("[{}] Prediction: {} True Y: {}".format(p == int(y), p, int(y)))




동물을 특징 짖는 여러 가지 X 값에 대한 결과 Y값을 가지고 있을 때, 즉 Multinomial Classification을 할 때 Fancy Softmax Classifier를 사용한다.






참조


김성훈교수님의 Softmax Classification을 Tensorflow로 구현하는 강좌

- 김성훈교수 강좌 정리한 글-1, 잘 정리한 글-2, 잘 정리한 글-3

- Github Softmax Classification 예제-1

posted by 윤영식