로지스틱 회귀 분류(Logistic Regression Classification) 연습

로지스틱 회귀 분류 모델

  • 가설식(Hypothesis)

\begin{eqnarray} H(x) = \frac{1}{1+e^{-(\mathbf{W}^\intercal \mathbf{X} + \mathbf{b})}}\tag{1}\end{eqnarray}

  • cost(loss) 함수

\begin{eqnarray}\textrm{cost}(W,b)=-\frac{1}{m}\sum \big( y\log H(x) + (1-y)\log (1-H(x))\big)\tag{2}\end{eqnarray}

  • 경사 하강법(Gradient Descent Algorithm)

\begin{eqnarray}W = W - \alpha \frac{\partial}{\partial W}\textrm{cost}(W,b)\end{eqnarray}



로지스틱 회귀 분류 모델을 사용한 기계 학습 연습

  • 학습에 사용할 데이터는 다음과 같다.

    • \(y\) 값은 항상 0과 1을 갖는다는 것이 중요하다
    • 데이터 사용 시 중요한 것은 모양(shape)이다.
x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]]
y_data = [[0], [0], [0], [1], [1], [1]]

X = tf.placeholder(tf.float32, shape=[None, 2])
Y = tf.placeholder(tf.float32, shape=[None, 1])
  • 전체  코드는 다음과 같다.

import tensorflow as tf

x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]]
y_data = [[0], [0], [0], [1], [1], [1]]

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

# weight의 shape은 X의 변수가 2개이기 때문에 [2, 1](2행 1열)이다.
W = tf.Variable(tf.random_normal([2, 1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')

# 가설식
hypothesis = tf.sigmoid(tf.matmul(X, W) + b)

# cost(loss) 함수
cost = -tf.reduce_mean(Y*tf.log(hypothesis) + (1-Y)*tf.log(1-hypothesis))

# 경사 하강법
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)
## 여기까지가 학습을 위한 그래프를 만들었다.

## 예측한 값을 가지고 성공했는지 실피했는지 bianry 출력해야한다.
## hypothesis를 계산하면 0과 1사이의 값이기 때문에 분류의 기준을 0.5로 설정
## 0.5보다 크면 성공, 작으면 실패

# cast() 메서드를 사용하면 결과값은 0.0 또는 1.0
predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)

# 예측값과 실제값이 같은지를 확인하여 맞을 확률을 구한다
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))

## 이제 학습을 시키자.
# 그래프를 만든다.
with tf.Session() as sess:
    # 변수 초기화
    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 % 2000 == 0:
            print(f"STEP = {step:06}, cost 함수값= {cost_val:1.14}")

    h, c, a = sess.run([hypothesis, predicted, accuracy], feed_dict={X: x_data, Y: y_data})

    print(f"\n가설식의 값 = {h},\n실제의 값 = {c},\n정확도 = {a}")

  • 결과값

STEP = 000000, cost 함수값= 0.53687995672226
STEP = 002000, cost 함수값= 0.3408930003643
STEP = 004000, cost 함수값= 0.25828701257706
STEP = 006000, cost 함수값= 0.20591051876545
STEP = 008000, cost 함수값= 0.17069421708584
STEP = 010000, cost 함수값= 0.14567981660366

가설식의 값 = [[ 0.0291514 ]
 [ 0.15663536]
 [ 0.29717436]
 [ 0.78491896]
 [ 0.94178247]
 [ 0.98091239]],
실제의 값 = [[ 0.]
 [ 0.]
 [ 0.]
 [ 1.]
 [ 1.]
 [ 1.]],
정확도 = 1.0



로지스틱 회귀 분류 모델을 실제 데이터에 적용하기

  • 학습에 사용할 데이터는 파일로 불러온다.

    • 당뇨병(diabete) 자료를 토대로 학습시켜 예측해보자.
import numpy as np

xy = np.loadtxt('data-03-diabetes.csv', delimiter=',', dtype=np.float32)
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]

  • 나머지 학습을 위한 코드는 이전과 동일!!!

    • 데이터를 불러오는 부분만 우리가 잘 설계하면 된다!!!!
    • 데이터의 변수 갯수가 몇 개인지 확인한 후에 모양(shape)을 정확하게 입력해야 한다.

import tensorflow as tf
import numpy as np

xy = np.loadtxt('data-03-diabetes.csv', delimiter=',', dtype=np.float32)
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]

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 = tf.sigmoid(tf.matmul(X, W) + b)

cost = -tf.reduce_mean(Y*tf.log(hypothesis) + (1-Y)*tf.log(1-hypothesis))
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)

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

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    feed = {X: x_data, Y: y_data}

    for step in range(10001):
        sess.run(train, feed_dict=feed)
        if step % 2000 == 0:
            print(f"STEP = {step:06}, cost 합수값 = {sess.run(cost, feed_dict=feed)}")

    h, c, a = sess.run([hypothesis, predicted, accuracy], feed_dict=feed)
    print(f"\n가설식의 값 = {h},\n\n실제의 값 = {c},\n\n정확도 = {a}")


STEP = 000000, cost 합수값 = 1.585148811340332
STEP = 002000, cost 합수값 = 0.5984190106391907
STEP = 004000, cost 합수값 = 0.5360344648361206
STEP = 006000, cost 합수값 = 0.5096880793571472
STEP = 008000, cost 합수값 = 0.4965749979019165
STEP = 010000, cost 합수값 = 0.48917973041534424

가설식의 값 = [[ 0.43279484]
 [ 0.92194134]
 [ 0.15470713]
 [ 0.93848407]
...
 [ 0.72711807]
 [ 0.75625086]
 [ 0.78592217]
 [ 0.69465518]
 [ 0.8947171 ]],

실제의 값 = [[ 0.]
 [ 1.]
 [ 0.]
 [ 1.]
 [ 0.]
...
 [ 1.]
 [ 1.]
 [ 1.]
 [ 1.]
 [ 1.]
 [ 1.]],

정확도 = 0.7628458738327026


+ Recent posts