관리 메뉴

ComputerVision Jack

[모두의 딥러닝 Chapter06] 본문

DeepLearning/DL_ZeroToAll

[모두의 딥러닝 Chapter06]

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

[06-1 softmax_classifier]

다분류기 모델

저번 모델은 이진 분류기를 사용하였다면 이번엔 다분류기를 사용하며 특성에 알맞게 다 클래스로 분류하는 과정이다.

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_data는 저번과 거의 비슷하지만 y_data가 조금은 다르다. 분류 결과를 통하여 도출 할 수 있는 그룹군은 총 3개이다.

그리고 각 클래스 별로 인덱스를 주어 라벨을 정의한다.

 

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

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

nb_classes = 3

#placeholder를 사용하여 x 데이터와 y데이터에 맞게 공간을 할당하고

분류될 클래스를 개수 만큼 변수에 저장해 둔다.

 

W = tf.Variable(tf.random_normal([4, nb_classes]), name ='weight')

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

#가중치와 편향 또한 설정한다. [none x 4] 이기 때문에 w는 [4, x]가 와야하는데 x로 도출될 결과 그룹이 3개이기 때문에 [4, 3]이 된다. 또한 편향도 3가지에 각각 들어가야하기 때문에 3으로 정의한다.

 

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

#활성 함수로 다분류기의 대표 softmax함수를 넣었다. softmax는 sigmoid활성함수를 여러개 달아 놓은 것과 같다.

 

cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis = 1))

optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.1).minimize(cost)

#손실 함수와 경사하강법을 구현한다.

 

with tf.Session() as sess:

  sess.run(tf.global_variables_initializer())

 

  for step in range(2001):

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

 

    if step % 200 == 0:

      print(step, cost_val)

 

  print('##########')

  #Testing & One-hot encoding

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

#학습을 시키면 원하는 결과에 맞게 분류가 되는 것을 볼 수 있다.

print()함수로 출력한 부분을 보면 결과 [x1, x2, x3] 인덱스중 분류값에 맞게 가장 높은 값에 있는 값을 가져와 분류한다.

[06-2 softmax_zoo_classifier]

실제 데이터에 적용한 softmax

from google.colab import files

uploaded = files.upload()

# colab으로 파일을 마찬가지로 읽어온다.

 

xy = np.loadtxt('data-04-zoo.csv', delimiter = ',', dtype = np.float32)

x_data = xy[:, 0: -1]

y_data = xy[:, [-1]]

#데이터에 맞게 x와 y를 슬라이싱으로 분류하고 저장한다.

 

Y_one_hot = tf.one_hot(Y, nb_classes)

print("one_hot : ", Y_one_hot)

Y_one_hot = tf.reshape(Y_one_hot, [-1, nb_classes])

print("reshape one_hot : ", Y_one_hot)

# 여기서 온핫 코딩이 사용되었는데, 우리가 원하는 index가 1이되도록 shape을 조금 번형해야한다.

one_hot : Tensor("one_hot_1:0", shape=(?, 1, 7), dtype=float32)

reshape one_hot : Tensor("Reshape:0", shape=(?, 7), dtype=float32)

과정을 거치면 shape이 변경되고 우리가 원하는 shape으로 도출 할 수 있다.

 

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = logits, labels = tf.stop_gradient([Y_one_hot])))

#전장의 조금 복잡했던 softmax cost함수를 함수화 한다. v2로 버전이 바뀌었으니 주의 하자.

 

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

# 모델의 정확도를 파악하기 위한 준비를 한다.

 

모델을 실행시키고 마지막 정확도를 볼때

 

  pred = sess.run(prediction, feed_dict = {X: x_data})

  for p, y in zip(pred, y_data.flatten()):

    print("[{}] Prediction : {} True Y : {}".format(p == int(y), p, int(y)))

 

#zip으로 던질때, y_data를 flatten 시킨다.

여기서 flatten은

[0]

[0]

[0]

으로 되어 있는 데이터를 [0, 0, 0,]으로 가로로 길게 늘리는 작업이라고 생각하면 된다.

06-1-softmax_classifier.ipynb
0.00MB
06-2-softmax_zoo_classifier.ipynb
0.02MB

반응형

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

[모두의 딥러닝 Chapter08]  (0) 2020.01.20
[모두의 딥러닝 Chapter07]  (0) 2020.01.19
[모두의 딥러닝 Chapter05]  (0) 2020.01.16
[모두의 딥러닝 Chapter04]  (2) 2020.01.15
[모두의 딥러닝 Chapter03]  (0) 2020.01.14
Comments