단일신경망 Single Layer Neural Network (ver. R)
출처¶
http://jorditorres.org/first-contact-with-tensorflow/#cap4 (First Contact with tensorflow)
https://tensorflow.rstudio.com/ (TensorFlow™ for R)
http://motioninsocial.com/tufte/ (Tufte in R)
단일 신경망 Single Layer Neural Network (ver.R)¶
The MNIST data-set¶
숫자 손글씨(hand-written digits)에 관한 엄청 유명한 데이터 셋.
training set으로 6만 개 이상, test set으로 1만 개이다.
흑백사진으로 이루어져있고, anti-aliasing 돼있다. 전 처리가 다 돼있기 때문에, 패턴 인식을 시작하는 사람들에게 이상적이라고 한다.
supervised learning의 한 예이다.
require(tensorflow)
datasets <- tf$contrib$learn$datasets
mnist <- datasets$mnist$read_data_sets("MNIST-data", one_hot = TRUE)
모형에 대한 자세한 설명은 생략하도록 하겠습니다.¶
Neural Network, activation function (softmax), loss function (cross-entropy), optimizer (gradient descent, batchsize) etc..
Single layer neural network¶
변수 지정
x <- tf$placeholder("float", shape(NULL, 784L))
W <- tf$Variable(tf$zeros(c(784L,10L)))
b <- tf$Variable(tf$zeros(10L))
모형 설정 Activation function : softmax
y <- tf$nn$softmax(tf$matmul(x, W) + b)
y_ <- tf$placeholder("float", shape(NULL,10))
Loss function : cross-entropy
cross_entropy <- tf$reduce_sum(y_ * tf$log(y))
Optimizer : Gradient Descent (learning_rate = 0.01)
train_step <- tf$train$GradientDescentOptimizer(0.01)$minimize(cross_entropy)
최적화 반복
sess <- tf$Session()
sess$run(tf$global_variables_initializer())
for (i in 0:100) {
batches <- mnist$train$next_batch(100L)
batch_xs <- batches[[1]]
batch_ys <- batches[[2]]
b_ys <- as.integer(batch_ys) ; dim(b_ys) <- dim(batch_ys)
sess$run(train_step,
feed_dict = dict(x = batch_xs, y_ = b_ys))
if(i %in% (0:20*5)){
correct_prediction <- tf$equal(tf$argmax(y,1L), tf$argmax(y_,1L))
accuracy <- tf$reduce_mean(tf$cast(correct_prediction, "float"))
print(c(i, sess$run(accuracy, feed_dict = dict(x = mnist$test$images,
y_ = mnist$test$labels))))
}
}
batch size = 100개로 하고, 계속 Gradient Descent를 반복하면서, 5의 배수일 때마다 test set의 정확도를 계산해서 출력한다. 정확도가 기껏해야 0.098로, 성능이 안 좋다는 것을 알 수 있다.