블로그 이미지
윤영식
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 윤영식

Linear Regression의 Tensorflow 실습 강좌를 정리해 본다. 





Hypothesis & Cost function (예측과 비용 함수)



학습을 통해 cost function의 W와 b를 minimized하는게 목적이다. 

- step-1: Node라는 operation 단위를 만든다. 

- step-2: Session.run을 통해 operation한다. 

- step-3: 결과값을 산출한다. 



Tensorflow는 W, b를 Variable로 할당한다. Variable이란 tensorflow가 변경하는 값이다라는 의미이다. 


H(x) 가설 구하기


$ python3

>>> import tensorflow as tf

>>> x_train = [1,2,3]

>>> y_train = [1,2,3]

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

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

>>> hypothesis = x_train * W + b


cost(W,b) 구하기

- reduce_mean: 전체 평균

- square: 제곱

>>> cost = tf.reduce_mean(tf.square(hypothesis - y_train))



minimize Cost 구하기

- GradienDescent 를 사용해서 minimize한다.

>>> optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)

>>> train = optimizer.minimize(cost)





Graph 실행하기


Tensorflow의 Session을 만들고, 글로벌 변수값을 초기화 해준다. 

- 2000번을 돌리면서 20번만다 출력해 본다. 

- sess.run(train): 학습을 시킨다. 처음 Cost를 랜덤하게 가면서 학습할 수록 값이 작이진다. 

   sess.run(W): 1에 수렴하고

   sess.run(b): 작은 값이 수렴한다.

>>> sess = tf.Session()

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

>>> for step in range(2001):

...     sess.run(train)

...     if step % 20 == 0:

...             print(step, sess.run(cost), sess.run(W), sess.run(b))

...

0 8.145951 [-0.13096063] [-0.43867812]

20 0.0741704 [0.87371004] [0.00051325]

40 0.0009571453 [0.9702482] [0.04034551]

   ... 생략 ...

1960 2.7972684e-08 [0.9998057] [0.00044152]

1980 2.5414716e-08 [0.99981487] [0.00042076]

2000 2.3086448e-08 [0.9998234] [0.00040107]


위의 train은 여러 Node가 연결된 graph가 된다. 






Placeholder로 수행하기


수행시 필요할 때 값을 동적으로 전달하여 train해 본다. 

- X, Y placeholder를 만든다. 

- feed_dict를 통해 값을 할당한다.

>>> X = tf.placeholder(tf.float32)

>>> Y = tf.placeholder(tf.float32)

>>> for step in range(2001):

...     cost_val, W_val, b_val, _ = sess.run([cost, W, b, train], feed_dict={X: [1,2,3], Y:[1,2,3]})

...     if step % 20 == 0:

...             print(step, cost_val, W_val, b_val)

...

0 2.3086448e-08 [0.9998238] [0.00040011]

20 2.0964555e-08 [0.99983215] [0.00038142]






참조


- 김성훈교수님의 Linear Regression의 Tensorflow 실습

- Github 실습 코드

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

인프런의 모두를 위한 딥러닝을 공부하기 위해 Tensorflow를 설치해 보았다. 





Python 설치


python은 3.6.6을 설치한다. 3.7를 설치하고 Tensorflow를 설치하니 오류가 있었다. 


- Python v3.6.6설치

- pip python package 매니져를 업데이트 한다. 

curl https://bootstrap.pypa.io/get-pip.py | python


- virtualenv를 통해 특정 폴더에 대해 python version을 적용한다. 맨뒤 옵션이 특정 폴더이다.

$ virtualenv --system-site-packages -p python3 /Users/prototyping/machine-learning

$ cd machine-learning 

$ source ./bin/activate

(machine-learning)

~/prototyping/machine-learning

$




Tensorflow 설치


pip3를 이용해서 설치하는 방법이 실패하여 직접 download url을 입력한다. 

$ pip3 install --upgrade tensorflow (실패하면 아래 직접 URL 지정한다)

$ pip3 install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.8.0-py3-none-any.whl



이제 시작해 보자...



참조


- Mac에서 virtualenv설치하기

posted by 윤영식
prev 1 2 next