개요(Abstract)
아래의 내용은 hunkim님의 모두를 위한 머신러닝/딥러닝 강의에서 tensorFlow 사용 예제를 R로 변경한 내용이다.
아래의 내용은 hunkim님의 모두를 위한 머신러닝/딥러닝 강의에서 tensorFlow 사용 예제를 R로 변경한 내용이다.
hunkim님의 강좌 주소는 http://hunkim.github.io/ml/ 이다.
아래의 내용은 ML의 실용과 몇가지 팁 수업에 있는 python 코드를 R로 변경한 것이다.
소스는 lab-09-1-xor_nn.py 이다.
아래의 내용은 XOR 문제를 해결하기 위해 신경망 방법의 예제이다.
learning_rate = 0.1인 경우 정확도가 있으나, 0.001이면 정확도가 낮다. learning_rate 값을 찾는 것이 문제이다.
tensorFlow에서는 cost함수를 사용할때 상당한 주의가 필요하다. 수식이 틀리면 수렴하지 않는다.
소스는 lab-09-1-xor_nn.py 이다.
아래의 내용은 XOR 문제를 해결하기 위해 신경망 방법의 예제이다.
learning_rate = 0.1인 경우 정확도가 있으나, 0.001이면 정확도가 낮다. learning_rate 값을 찾는 것이 문제이다.
tensorFlow에서는 cost함수를 사용할때 상당한 주의가 필요하다. 수식이 틀리면 수렴하지 않는다.
library(tensorflow)
# import numpy as np
x_data = matrix(c(0, 0, 0, 1, 1, 0, 1, 1), byrow = 2, ncol = 2)
y_data = matrix(c(0, 1, 1, 0))
X = tf$placeholder(tf$float32, shape=list(NULL, 2))
Y = tf$placeholder(tf$float32, shape=list(NULL, 1))
W1 = tf$Variable(tf$random_normal(shape=list(2L, 2L)), name="weight")
b1 = tf$Variable(tf$random_normal(shape=list(2L)), name="bias")
layer1 = tf$sigmoid(tf$matmul(X, W1) + b1)
W2 = tf$Variable(tf$random_normal(shape=list(2L, 1L)), name="weight")
b2 = tf$Variable(tf$random_normal(shape=list(1L)), name="bias")
hypothesis = tf$sigmoid(tf$matmul(layer1, W2) + b2)
# cost/loss function
cost = - tf$reduce_mean(Y * tf$log(hypothesis) + (1 - Y) * tf$log(1 - hypothesis))
train = tf$train$GradientDescentOptimizer(learning_rate=0.1)$minimize(cost)
# Accuracy computation
# True if hypothesis>0.5 else False
predicted = tf$cast(hypothesis > 0.5, dtype=tf$float32)
accuracy = tf$reduce_mean(tf$cast(tf$equal(predicted, Y), dtype=tf$float32))
sess <- tf$Session()
# Initialize TensorFlow variables
sess$run(tf$global_variables_initializer())
for (step in 1: 10001) {
# c_val, _ = sess$run([cost, train], feed_dict={X: x_data, Y: y_data})
stage = sess$run(list(cost, train), feed_dict=dict(X = x_data, Y = y_data))
if (step %% 100 == 0) {
cat("step:", step, "cost:", stage[[1]], "\n" )
}
}
# Accuracy report
pred = sess$run(list(hypothesis, predicted, accuracy), feed_dict=dict(X = x_data, Y = y_data))
names(pred) <- c("Hypothesis", "Correct", "Accuracy")
(pred)
sess$close()
print("END OF CODE")
댓글 없음:
댓글 쓰기