해당 자료는 "모두를 위한 머신러닝/딥러닝 강의"를 보고 개인적으로 정리한 내용입니다.
본 실습의 tensorflow는 1.x 버전입니다.
Softmax Classification 코드 구현
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
#tensorflow v1호환
import numpy as np
# Predicting animal type based on various features
xy = np.loadtxt('data-04-zoo.csv', delimiter=',', dtype=np.float32)
#x_data = xy[:, 0:-1] 에서 [:, 부분은 xy 이중 리스트의 모든 행을 나타냄
#x_data = xy[:, 0:-1] 에서 ,0:-1] 부분은 xy 이중 리스트의 열중 처음부터 뒤에서 첫번째 전까지를 나타냄
x_data = xy[:, 0:-1]
#y_data = xy[:, [-1]] 에서 [:, 부분은 xy 이중 리스트의 모든 행을 나타냄
#y_data = xy[:, [-1]] 에서 , [-1] 부분은 xy 이중 리스트의 열중 뒤에서 첫번째를 나타냄
y_data = xy[:, [-1]]
nb_classes = 7 # 0 ~ 6
X = tf.placeholder(tf.float32, [None, 16])
# xy에서 Y는 0~6까지의 숫자를 가짐
# 행은 여러개 이므로 None로 정의
# shape = [None, 1]
Y = tf.placeholder(tf.int32, [None, 1]) # 0 ~ 6
# 0~6의 숫자를 0과 1의 구성으로 만들기 위해 one_hoe 함수 사용
# tf.one_hot(Y, nb_classes) 는 Y(0~6)의 값을 총 7개의 0과 1로 구성된 형태로 변경해라라는 의미
# 단, one_hot 함수를 사용하면 rank가 N => N+1이 되기 때문에 아래 reshape을 통해 rank를 변경
# ex) [[0], [3]] 인 shape 이 [2,1]이고 rank가 2인 리스트를 one_hot(Y,7) 함수를 사용하는 경우
# ===> [[[1,0,0,0,0,0,0]],[[0,0,0,1,0,0,0]]] 인 shape가 [2,1,7] 이고 rank가 3이 됨
Y_one_hot = tf.one_hot(Y, nb_classes) # one hot
# reshape를 통해 [-1, 7] 형태로 변경. -1은 정해진 값에 의해 알아서 값이 결정
# reshape를 통해 [[1,0,0,0,0,0,0],[0,0,0,1,0,0,0]] 인 shape가 [2, 7] 이고 rank가 2가 됨
Y_one_hot = tf.reshape(Y_one_hot, [-1, nb_classes])
# X의 행은 None 이고 열은 16개, Y는 행이 None이고 열이 7개
# W는 매트릭스 곱에 의해 [16,7]
W = tf.Variable(tf.random_normal([16, nb_classes]), name='weight')
b = tf.Variable(tf.random_normal([nb_classes]), name='bias')
# logits는 score를 나타냄
# score를 softmax 함수를 통해 0 또는 1로 변환
# tf.nn.softmax computes softmax activations
# softmax = exp(logits) / reduce_sum(exp(logits), dim)
logits = tf.matmul(X, W) + b
hypothesis = tf.nn.softmax(logits)
# 이전의 cross entropy 함수는 아래처럼 사용가능
# cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1))
# 텐서플로우에서는 위 계산을 -tf.reduce_sum(Y * tf.log(hypothesis), axis=1)를 softmax_cross_entropy_with_logits 함수로 제공
# Cross entropy cost/loss
cost_i = tf.nn.softmax_cross_entropy_with_logits(logits=logits,
labels=Y_one_hot)
# softmax_cross_entropy_with_logits 함수로 얻은 cost들의 평균값을 구함
cost = tf.reduce_mean(cost_i)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
# 예측값인 hypothesis를 argmax로 0~6사이의 값으로 변환
prediction = tf.argmax(hypothesis, 1)
# Y_one_hot은 실제 값으로 argmax으로 0~6사이의 값으로 변환. 즉 one_hot 함수 사용 전 값
correct_prediction = tf.equal(prediction, tf.argmax(Y_one_hot, 1))
# 예측값과 실제 Y값이 맞는 애들의 평균
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# Launch graph
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for step in range(2000):
#학습
sess.run(optimizer, feed_dict={X: x_data, Y: y_data})
if step % 100 == 0:
loss, acc = sess.run([cost, accuracy], feed_dict={
X: x_data, Y: y_data})
print("Step: {:5}\tLoss: {:.3f}\tAcc: {:.2%}".format(
step, loss, acc))
# 학습한 모델에 x_data를 던져서 예측 결과 추출
# Let's see if we can predict
pred = sess.run(prediction, feed_dict={X: x_data})
# flatten()을 사용하면 [[A]],[B]] 를 [A,B] 의 형태로 변경
# y_data: (N,1) = flatten => (N, ) matches pred.shape
for p, y in zip(pred, y_data.flatten()):
print("[{}] Prediction: {} True Y: {}".format(p == int(y), p, int(y)))
rank, shape 개념 정리
2020/04/13 - [데이터/모두를 위한 머신러닝] - ML lab 01 - TensorFlow의 설치및 기본적인 operations
'도서,강의 요약 > 모두를 위한 머신러닝' 카테고리의 다른 글
lec 07-2: Training/Testing 데이타 셋 (0) | 2020.06.20 |
---|---|
lec 07-1: 학습 rate, Overfitting, 그리고 일반화 (Regularization) (0) | 2020.06.15 |
ML lab 06-1: TensorFlow로 Softmax Classification의 구현하기 (0) | 2020.06.03 |
ML lec 6-2: Softmax classifier 의 cost함수 (0) | 2020.05.30 |
ML lec 6-1 - Softmax Regression: 기본 개념 소개 (0) | 2020.05.28 |