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

Publication

Category

Recent Post

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 윤영식

여러개의 Classification 강좌를 정리한다. 





Logistic Regression


Y hat 은 예측이다. 두가지를 구분하는 선을 찾아내기를 학습한다. 

즉, Multinomial 을 0 또는 1을 만들고 이들을 구분하는 선을 찾는 것이다.




세번의 독립된 binary classification을 구한다. 

- A 이거나 not 아니거나

- B 이거나 not 아니거나

- C 이거나 not 아니거나 

개별적인 것을 Matrix로 표현한다.




Softmax를 이용한 단순화하기 


전체 값을 합치면 1이 되는 함수 = Softmax classifier (강좌)


예측 모델



0.7, 0.2, 0.1은 확률값과 같고 이를 classification하면 다음과 같이 a가 1이되고 나머지는 0이 된다. 

여기서 "One-Hot Encoding"을 이용하여 1 또는 0의 예측을 구한다.




Cost function


예측과 실제값의 비용함수를 구하기 위해 "Cross-Entropy"를 사용한다. Cost function의 결과값이 작으면 예측이 맞는 것이다. 크면 예측이 맞지 않는 것이다.

- D: 차이 Distance


하나에 대한 것은 기존의 Logistic cost function과 cross entropy공식은 같다. 



여러 Training set을 넣을 때 거리의 합에 대한 평균을 구한다. Loss (Cost) function 을 최종적으로 얻을 수 있다. 





Gradient Descent 적용


Cost function을 미분하면서 기울기가 가장 작은 값의 W값을 찾는다. 






참조


- 김성훈교수님의 Multinomial Classification 강좌

- 김성훈교수님의 Multinomial Classification의 Cost Function 강좌

posted by 윤영식

Logistic Classification 강좌를 정리한다. 




Regression vs Classification


- Regression: 숫자를 예측

- Classification: 정해진 카테고리를 정하는 것: Pass(1) 또는 Fail(0) 으로 판단한다.

   ex) Spam Detection, Facebook feed, Credit Card Fraud Detection


Linear Regression에서 x값이 너무 커서 Output이 1보다 커지는 것을 방지하기 위해 H(x) 를 z로 놓고, g(z)의 결과가 0 ~ 1 사이에 수렴되는 것을 sigmoid(시그모이드) 함수라 하고, Logistic function 이라고도 한다. 



수식은 다음과 같다. 







New Cost function for Logistic Classification


기존 Linear Regression과 Sigmoid function을 적용했을 때의 모습

- 기울기가 평평해 지는 지점에서 멈춤. 그러나 sigmoid에서는 기존 cost function을 적용하면 울퉁 불퉁하므로 시작점에 따라서 종료점(최소) 구간이 틀려질 수 있다. 즉 training을 멈추게 된다. 


따라서 Hypethesis를 변경했기 때문에 Cost function도 변경한다. 

- y:1 일때 예측이 틀릴경우 즉 H(x) = 0이면 cost 는 무한대가 된다. 

- y:0 일때 H(x) =0 이면 cost는 0이되고, H(x) = 1 이면 cost는 무한대가 된다. 

즉 잘 못 예측되면 cost가 무한대로 커진다. 


위의 수식을 y=0일때와 y=1일때 합치면 경사타고 내려가기인 그릇모양이 된다. 


공식에 대한 구현 코드는 다음과 같다. 






Logistic classifier를 Tensorflow로 구현하기


Y데이터 값으로 0 또는 1을 가지면 binary classification이다. None은 n개를 의미한다. (예제)



수식을 tensorflow 코드로 구현한다. 

- placeholder를 만들고

- sigmoid (logistic) function 구현

- new cost function 구현

- GradientDescenOptimizer를 이용한 경사 내려가기 미분 구현


결과: 1=true, 0=false 




예제

import tensorflow as tf

import numpy as np

tf.set_random_seed(777)  # for reproducibility


xy = np.loadtxt('data-03-diabetes.csv', delimiter=',', dtype=np.float32)

x_data = xy[:, 0:-1]

y_data = xy[:, [-1]]


print(x_data.shape, y_data.shape)


# placeholders for a tensor that will be always fed.

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

Y = tf.placeholder(tf.float32, shape=[None, 1])


W = tf.Variable(tf.random_normal([8, 1]), name='weight')

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


# Hypothesis using sigmoid: tf.div(1., 1. + tf.exp(-tf.matmul(X, W)))

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


# cost/loss function

cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) *

                       tf.log(1 - hypothesis))


train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)


# Accuracy computation

# True if hypothesis>0.5 else False

predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)

accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))


# Launch graph

with tf.Session() as sess:

    # Initialize TensorFlow variables

    sess.run(tf.global_variables_initializer())


    for step in range(10001):

        cost_val, _ = sess.run([cost, train], feed_dict={X: x_data, Y: y_data})

        if step % 200 == 0:

            print(step, cost_val)


    # Accuracy report

    h, c, a = sess.run([hypothesis, predicted, accuracy],

                       feed_dict={X: x_data, Y: y_data})

    print("\nHypothesis: ", h, "\nCorrect (Y): ", c, "\nAccuracy: ", a)





참조


- 김성훈교수님의 Logistic Classification 함수 강좌

- Github Logistic regression classification 예제, 파일 읽기 예제

posted by 윤영식

Multi Variable Linear Regression 강좌를 정리한다. 





Linear Regression 기본 개념

- Hypothesis: H(x) = Wx + b   => Input값을 통해 가설을 세운다. W, b에 따라 선의 모양일 달라진다.

- Cost function: cost(W,b) = H(x) - y 실제값의 차에 대한 제곱에 평균   =>    결과값을 바탕으로 가설을 검증하고 가장 적은 값을 갖는 W, b를 구한다. (참조)

- Gradient descent algorithm: 미분의 기울기에 따른 아래로 수렴되는 알고리즘  => Cost function을 최소화 하기 위한 최적화 알고리즘을 사용한다. (참조)

   -> 그릇처럼 밑으로 수렴되는 Convex Fuction을 사용하여 오류를 제거한다.


기존은 하나의 Input variable만 사용했다면 여러개의 multi variable에 대한 예측



변수(Variable)이 여러개(Multi)일 때 Matrix를 이용한다. Matrix를 사용할 때는 X가 앞에 오고 W가 뒤에 온다. + b 가 없을 때 수식은 아래와 같다. 



(x1, x2, x3)를 하나의 Instance라고 부른다. Instance가 많을 경우 다음과 같은 수식을 사용한다. W는 동일하다. 

- X: [Instance, #x]

- W: [#w, #]

연산시 #x와 #w의 숫자는 같아야 한다. 계산 결과는 [instance, #] 이 된다. 




위의 5값은 instance의 갯수는 가변이므로 n으로 표현한다. 보통 Tensorflow에서 None으로 표현하면 n개를 말한다. 그리고 n Output의 경우일때는 다음과 같다.



이론과 실제 구현상 공식. 수학적 의미는 거의 같다.







Tensorflow 실습하기 


x1, x2, x3 instance가 있고, 결과 Y 하나가 나온다.


 Maxtrix를 이용해서 구현해 본다. (예제)


import tensorflow as tf

tf.set_random_seed(777)  # for reproducibility


x_data = [[73., 80., 75.],

          [93., 88., 93.],

          [89., 91., 90.],

          [96., 98., 100.],

          [73., 66., 70.]]

y_data = [[152.],

          [185.],

          [180.],

          [196.],

          [142.]]



# placeholders for a tensor that will be always fed.

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

Y = tf.placeholder(tf.float32, shape=[None, 1])


W = tf.Variable(tf.random_normal([3, 1]), name='weight')

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


# Hypothesis

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


# Simplified cost/loss function

cost = tf.reduce_mean(tf.square(hypothesis - Y))


# Minimize

optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)

train = optimizer.minimize(cost)


# Launch the graph in a session.

sess = tf.Session()

# Initializes global variables in the graph.

sess.run(tf.global_variables_initializer())


for step in range(2001):

    cost_val, hy_val, _ = sess.run([cost, hypothesis, train], feed_dict={X: x_data, Y: y_data})

    if step % 10 == 0:

        print(step, "Cost: ", cost_val, "\nPrediction:\n", hy_val)


==> 결과

... 


2000 cost:  7.4047155

prediction:

 [[154.63629]

 [182.36778]

 [181.60802]

 [197.86899]

 [137.86888]]






파일에서 읽어 실행하기 


Python 의 numpy를 이용하여 읽어오고 slicing한다. (예제)


import numpy as np


xy = np.loadtxt('data-01-test-score.csv', delimiter=',', dtype=np.float32)

x_data = xy[:, 0:-1] # slicing

y_data = xy[:, [-1]]


읽을 내용이 많을 경우 한번에 가져오지 않고 Queuing하여 처리하는 Queue Runners를 제공한다. (예제)

Step-1: 여러개의 파일을 읽어온다. 

Step-2: 파일에서 key, value을 가져온다. 

Step-3: 값을 decoding한다.



import tensorflow as tf

tf.set_random_seed(777)  # for reproducibility


filename_queue = tf.train.string_input_producer(['data-01-test-score.csv'], shuffle=False, name='filename_queue')


reader = tf.TextLineReader()

key, value = reader.read(filename_queue)


# Default values, in case of empty columns. Also specifies the type of the

# decoded result.

record_defaults = [[0.], [0.], [0.], [0.]]

xy = tf.decode_csv(value, record_defaults=record_defaults)


# collect batches of csv in

train_x_batch, train_y_batch = tf.train.batch([xy[0:-1], xy[-1:]], batch_size=10) #10 개씩 처리 


# placeholders for a tensor that will be always fed.

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

Y = tf.placeholder(tf.float32, shape=[None, 1])


W = tf.Variable(tf.random_normal([3, 1]), name='weight')

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


# Hypothesis

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


# Simplified cost/loss function

cost = tf.reduce_mean(tf.square(hypothesis - Y))


# Minimize

optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)

train = optimizer.minimize(cost)


# Launch the graph in a session.

sess = tf.Session()

# Initializes global variables in the graph.

sess.run(tf.global_variables_initializer())


# Start populating the filename queue.

coord = tf.train.Coordinator()

threads = tf.train.start_queue_runners(sess=sess, coord=coord)


for step in range(2001):

    x_batch, y_batch = sess.run([train_x_batch, train_y_batch])

    cost_val, hy_val, _ = sess.run(

        [cost, hypothesis, train], feed_dict={X: x_batch, Y: y_batch})

    if step % 10 == 0:

        print(step, "Cost: ", cost_val, "\nPrediction:\n", hy_val)


coord.request_stop()

coord.join(threads)


# Ask my score

print("Your score will be ",

      sess.run(hypothesis, feed_dict={X: [[100, 70, 101]]}))


print("Other scores will be ",

      sess.run(hypothesis, feed_dict={X: [[60, 70, 110], [90, 100, 80]]}))





참고


- 김성훈교수님의 Multi-Variable linear regression 강좌

- Github 예제 4-1

- Github 예제 4-2 using Matrix

- 선형 & 다중 회귀분석


posted by 윤영식

Tensorflow를 이용해 Minimized Cost를 구하는 Algorithm실습 강좌를 정리한다.





Matplotlib 을 이용한 차팅


Python을 통해 그래프를 그리기 위해 matplotlib을 가이드에따라 설치한다. 

$ python -mpip install -U matplotlib


다음으로 ~/.matplotlib 밑에 matplotlibrc  파일을 생성하고 다음 내역을 작성한다. (참조)

backend: TkAgg


다음 코드를 작성하고 실행한다. 

W = 1 이 최소화를 위한 값이라는 것을 알 수 있다.






"W := W - 미분값" 이해


- 미분값은 경사도를 의미하고 좌에서 우로 내려가면 - 값, 좌에서 우로 올라가면 + 값이다.

- 마이너스 값이 되면 W + 미분값이 되어 W가 큰값으로 옮겨가고, W - 미분값은 W가 작은 값으로 수렴한다. 

  + a 알파값: learning-rate 상수값

  + = 은 assign펑션을 이용해 descent를 update에 할당한다. 

  + update operation를 run하면 graph를 통해 일련의 동작이 일어난다.  


Graph를 실행하는 단계

- Session생성

- 글로벌 값 초기화

- session.run 으로 Node (operation)수행



직접 미분을 구현하지 않고 위처럼 GradientDescentOptimizer를 사용할 수 있다.  만일 gradient값을 수정하고 싶을 때는 compute_gradient(cost)로 얻은 값을 직접 수정하여 적용할 수 있다.

gvs = optimizer.compute_gradient(cost)

// gvs를 customizing한다. 

apply_gradients = optimizer.apply_gradients(gvs)


....

sess.run(apply_gradients)






참조


김성훈교수님의 Minimized Cost function 실습 강좌

- Lab-03-2-minimizing_cost_show_graph.py

posted by 윤영식

성김님의 Linear Regression강좌 개념을 정리해 본다. 





Regression


- 범위에 관한 문제를 다룬다. 예측을 위한 기본적인 범위(x)를 통해 결과(y)에 대한 학습을 수행한다.

- Linear Regression 가설

  + 예: 학생이 공부를 많이 할 수록 성적이 높아지고, 훈련을 많이할 수록 기록이 좋아진다.

  + 아래와 같은 선을 찾는 것이 Linear Regression의 목적이다. 



H(x): 우리가 세운 가설

Wx: x 값

W, b 에 따라 선의 모양이 달라진다. 


예) 파란선: H(x) = 1 * x + 0

     노란선: H(x) = 0.5 * x + 2





Cost function


Linear Regression의 가설 선과 실제 값사이의 거리가 가까우면 잘 맞은 것이고, 아니면 잘 맞지 않은 것 일 수 있다. 이를 계산하는 산술식을 Cost(Lost) function이라 한다. 


- 예측값 H(x) 와 실제값 y 를 뺀 후 제곱을 한다. 제곱을 하는 이유는

  + 음수를 양수로 만들고

  + 차이에 대한 패널티를 더 준다. 

  cost = (H(x) - y) 2



수식에 대한 일반화



최종 목표는 W, b에 대해 가장 작은 값을 학습을 통해 찾는 것이다. - Goal: Minimize cost



minimize cost(W, b)





참조


- 김성훈교수님의 Linear Regression


posted by 윤영식
prev 1 next