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

Publication

Category

Recent Post

여러개의 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 윤영식

Cost를 Minimize하는 방법 강좌를 정리한다. 





가설(Hyperthesis) 단순화


b를 제거하고 cost(W)에 대해 구한다. 이때 최소화 되는 구간을 찾는다. 그래프상으로 Y축 cost(W)와 X축 W의 관계에서 cost(W) = 0  인 지점이 최소화 지점이다. 



경사를 따라 내려가는 알고리즘 = Gradient Descent Algorithm 을 사용한다.

- 경사도가 있는 곳을 따라 움직이면서 cost를 줄인다. 미분이 경사도를 구하는 공식임.

- 즉, 해당 점의 기울기를 구한다.


Gradient Descent Algorithm Formal





Convex function


Cost function을 3차원으로 그렸을 때, 내려가는 경사를 잘 못 잡으면 내려간 곳의 W, b값이 틀려 질 수 있다. 알고리즘이 잘 동작하지 않는 예


Convex function을 통해 그릇형태로 만들어 어디를 내려오던 원하는 지점으로 수렴할 수 있다. Cost function을 만든 후 검증할 때 Convex function이 된다면 Linear Regression의 cost function은 잘 된 것으로 판명된다. 







참조


- 김성훈교수님의 Minimize Cost 강좌

posted by 윤영식