Softmax Regression (Multinomial Logistic Regression) PART 1


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

아래의 내용은 Softmax Regression (Multinomial Logistic Regression) 수업에 있는 python 코드를 R로 변경한 것이다.
변환하면서 R과 tensorFlow 간 integer 간 호환에 문제가 있어 LONG 타입으로 선언해야 했다.
# Lab 6 Softmax Classifier
library(tensorflow)

tf$set_random_seed(777)  # for reproducibility

x_data = rbind(c(1, 2, 1, 1),
               c(2, 1, 3, 2),
               c(3, 1, 3, 4),
               c(4, 1, 5, 5),
               c(1, 7, 5, 5),
               c(1, 2, 5, 6),
               c(1, 6, 6, 6),
               c(1, 7, 7, 7) )
y_data = rbind(c(0, 0, 1),
               c(0, 0, 1),
               c(0, 0, 1),
               c(0, 1, 0),
               c(0, 1, 0),
               c(0, 1, 0),
               c(1, 0, 0),
               c(1, 0, 0))


# long 타입으로 선언해야 에러 안남.
# 4 X, 4L O
X = tf$placeholder(tf$float32, list(NULL, 4L))
Y = tf$placeholder(tf$float32, list(NULL, 3L))
nb_classes = 3L

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


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


# Cross entropy cost/loss
# reduce 접두어는 수학 기호 시그마를 나타냄
# cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis)), axis=1)
cost = tf$reduce_mean(-tf$reduce_sum(Y * tf$log(hypothesis), axis=1L))

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

sess <- tf$Session()
sess$run(tf$global_variables_initializer())

for (step in 1:2001) {
    stage = sess$run(list(optimizer, cost), dict(X = x_data, Y = y_data))
    
    if (step %% 200 == 0)
        cat(step, unlist(stage[[2]]), "\n")
}
    



cat('--------------', "\n")
# Testing & One-hot encoding
a = sess$run(hypothesis, dict(X = matrix(c(1, 11, 7, 9), ncol = 4) ))
cat("a: ", sess$run(tf$argmax(a, 1L)), "\n")

cat('--------------', "\n")
b = sess$run(hypothesis, dict(X = matrix(c(1, 3, 4, 3), ncol = 4) ))
cat("b: ", sess$run(tf$argmax(b, 1L)), "\n")

cat('--------------', "\n")
c = sess$run(hypothesis, dict(X = matrix(c(1, 1, 0, 1), ncol = 4) ))
cat("c: ", sess$run(tf$argmax(c, 1L)), "\n")

cat('--------------', "\n")
all = sess$run(hypothesis, dict(X = matrix(c(1, 11, 7, 9, 1, 3, 4, 3, 1, 1, 0, 1), ncol = 4) ))
cat("all: ", sess$run(tf$argmax(all, 1L)), "\n")

sess$close()

print("END OF CODE")


댓글 없음:

댓글 쓰기