Softmax Regression (Multinomial Logistic Regression) PART 2


개요(Abstract)
아래의 내용은 hunkim님의 모두를 위한 머신러닝/딥러닝 강의에서 tensorFlow 사용 예제를 R로 변경한 내용이다.
hunkim님의 강좌 주소는 http://hunkim.github.io/ml/ 이다.

아래의 내용은 Softmax Regression (Multinomial Logistic Regression) 수업에 있는 python 코드를 R로 변경한 것이다. 소스는 lab-06-2-softmax_zoo_classifier.py 이다.
변환하면서 R과 tensorFlow 간 integer 간 호환에 문제가 있어 LONG 타입으로 선언해야 했다. 그리고 tensorFlow는 R의 data.frame 타입을 허용하지 않는다. matrix만 허용한다. 이 원인을 찾기 위해 조금 수고 했다. 주의가 필요하다.
library(tensorflow)


# numpy library는 R에 없음
# xy = np.loadtxt('', delimiter=',', dtype=np.float32)
# 프로젝트 디렉토리 아래 data 폴더의 파일 읽음
xy <- read.csv2(file = "./data/data-04-zoo.csv", skip = 19, sep = ",", header = FALSE)

(xy)

#    V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17
# 1   1  0  0  1  0  0  1  1  1   1   0   0   4   0   0   1   0
# 2   1  0  0  1  0  0  0  1  1   1   0   0   4   1   0   1   0
# 3   0  0  1  0  0  1  1  1  1   0   0   1   0   1   0   0   3
# 4   1  0  0  1  0  0  1  1  1   1   0   0   4   0   0   1   0
# 5   1  0  0  1  0  0  1  1  1   1   0   0   4   1   0   1   0
# 6   1  0  0  1  0  0  0  1  1   1   0   0   4   1   0   1   0

# R에서는 - 는 제외 연산자, python과 다름
# tensorflow에서는 data.frame 형식이 에러 남, matrix로 변경해야 함
x_data = as.matrix(xy[, 0:(ncol(xy) - 1)])
y_data = as.matrix(xy[, ncol(xy)])


# matrix와 vector 차원 확인
# dim(x_data)
# length(y_data)
# table(y_data)

nb_classes = 7L # 0 ~ 6

X = tf$placeholder(tf$float32, shape = list(NULL, 16L))
Y = tf$placeholder(tf$float32, shape = list(NULL, 1L))

# integer type 주의
Y_one_hot = tf$one_hot(y_data, nb_classes)
Y_one_hot = tf$reshape(Y_one_hot, shape = list(-1L, nb_classes))

colnames(Y_one_hot) <- NULL

# sess$run(Y_one_hot)

W = tf$Variable(tf$random_normal(shape = list(16L, nb_classes)), name="weight")
b = tf$Variable(tf$random_normal(shape = list(nb_classes)), name="bias")

# tf.nn.softmax computes softmax activations
# softmax = exp(logits) / reduce_sum(exp(logits), dim)
logits = tf$matmul(a = X, b = W) + b

# 아래 라인 중요
# hypothesis = tf$nn$softmax(logits)
hypothesis = tf$nn$softmax(tf$matmul(X, W) + b)

# Cross entropy cost/loss
cost = tf$reduce_mean(tf$nn$softmax_cross_entropy_with_logits_v2(logits=logits,
                                                                 labels=tf$stop_gradient(Y_one_hot)))

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


# tensorflow의 arg_max가 tf$math$argmax로 변경됨
prediction = tf$math$argmax(hypothesis, 1L)
correct_prediction = tf$equal(prediction, tf$argmax(Y_one_hot, 1L))
accuracy = tf$reduce_mean(tf$cast(correct_prediction, tf$float32))


sess <- tf$Session()
# train, etc.
sess$run(tf$global_variables_initializer())

for (step in 1:2001) {
    # stage <- 1
    stage = sess$run(list(optimizer, cost, accuracy), feed_dict = dict(X = x_data, Y = y_data))

    # % -> %% 
    # step <- 1
    if (step %% 100 == 0) {
        # print("Step: {:5}\tCost: {:.3f}\tAcc: {:.2%}".format(step, cost_val, acc_val))
        cat("Step: ", step, "\tCost: ", format(stage[[2]], digits=4), "\tAcc: ", format(stage[[3]], digits=4), " %\n", sep = "")
    }
        
    
}

# 예측
pred = sess$run(prediction, feed_dict=dict(X = x_data))

# python 코드와 많이 달라짐
acc <- table(PRED = pred, OBSRV = y_data)

# 예측 정확도
sum(diag(acc)) / sum(acc)
# [1] 1 => 100 % 일치

sess$close()

print("END OF CODE")

댓글 없음:

댓글 쓰기