관리 메뉴

ComputerVision Jack

[모두의 딥러닝 Chapter05] 본문

DeepLearning/DL_ZeroToAll

[모두의 딥러닝 Chapter05]

JackYoon 2020. 1. 16. 15:47
반응형

[05-1 Logistic_Regression]

logistic_regresssion은 이진 분류기를 뜻한다.

binary classificaiton

 

x_data = [[1, 2],

          [2, 3],

          [3, 1],

          [4, 3],

          [5, 3],

          [6, 2]]

y_data = [[0],

          [0],

          [0],

          [1],

          [1],

          [1]]

#x_data 한 묶음이 y_data 하나와 매칭이 된다.

전의 데이터는 회귀 예측이기 때문에 라벨이 1 0이 아닌 특정한 value로 되어 있었다.

 

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

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

#마찬가지로 x_data와 y_data(라벨)의 shape에 맞게 placeholder를 제작한다.

 

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

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

#가중치와 편향을 지정한다. shape의 모양을 따르고 출력 모양을 고려하여 선정하는 것을 잊지 말자.

 

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

# 제작 할 모델이 회귀와는 조금 다르다. 

행렬 연산을 하고 그것을 sigmoid라는 활성 함수에 넣는 것을 볼 수 있다.

sigmoid

sigmoid 활성함수의 모양이다. 따라서 우리의 출력결과가 0.5보다 크면 1을 내보내고

0.5보다 작으면 0을 내보낸다. (이렇게 하기 때문에 2진 분류가 완성된다.)

 

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

#그에 맞게 cost함수도 설정한다. log를 사용하여 우리가 원하는 이차함수 모양이 나오도록 한다.

 

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

#learning_rate을 설정하고 경사 하강법을 사용해서 train한다.

 

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

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

#예측을 토대로 정확성을 알 수 있게 만든다.

tf.cast함수를 사용하여 0.5 이상 이하의 값을 1과 0으로 만든다.

정확도는 우리의 예측과 실제 라벨의 차이를 고려해 그 값을 평균내어 판별한다.

 

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)

#학습을 시키고 결과를 출력하면 이진 분류기가 정상 작동 되는 것을 알 수 있다.

[05-2 logistic_regression_diabetes]

실제 데이터를 추가하여 이진 분류기를 사용해본다.

 

from google.colab import files

uploaded = files.upload()

#코렙에서 파일을 읽어 올 수 있게 사용한다.

 

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)

#데이터를 읽어오면 shape을 찍어서 placeholder와 weight설정 할 때 참고하자.

 

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')

# 읽어온 diabetes.csv에 맞는 data shape과 weight 설정

05-1-logistic_regression.ipynb
0.01MB
05-2-logistic_regression_diabetes.ipynb
0.03MB

반응형

'DeepLearning > DL_ZeroToAll' 카테고리의 다른 글

[모두의 딥러닝 Chapter07]  (0) 2020.01.19
[모두의 딥러닝 Chapter06]  (0) 2020.01.17
[모두의 딥러닝 Chapter04]  (2) 2020.01.15
[모두의 딥러닝 Chapter03]  (0) 2020.01.14
[모두의 딥러닝 Chapter02]  (0) 2020.01.13
Comments