Tensorflow/Tensorflow for R

단일신경망 Single Layer Neural Network (ver. R)

딥스탯 2017. 6. 24. 17:34
Untitled

단일 신경망 Single Layer Neural Network (ver.R)

The MNIST data-set

숫자 손글씨(hand-written digits)에 관한 엄청 유명한 데이터 셋.

training set으로 6만 개 이상, test set으로 1만 개이다.

흑백사진으로 이루어져있고, anti-aliasing 돼있다. 전 처리가 다 돼있기 때문에, 패턴 인식을 시작하는 사람들에게 이상적이라고 한다.

supervised learning의 한 예이다.

In [1]:
require(tensorflow)
datasets <- tf$contrib$learn$datasets
mnist    <- datasets$mnist$read_data_sets("MNIST-data", one_hot = TRUE)
Loading required package: tensorflow

모형에 대한 자세한 설명은 생략하도록 하겠습니다.

Neural Network, activation function (softmax), loss function (cross-entropy), optimizer (gradient descent, batchsize) etc..

Single layer neural network

변수 지정

In [2]:
x <- tf$placeholder("float", shape(NULL, 784L))
W <- tf$Variable(tf$zeros(c(784L,10L)))
b <- tf$Variable(tf$zeros(10L))

모형 설정 Activation function : softmax

In [3]:
y  <- tf$nn$softmax(tf$matmul(x, W) + b)
y_ <- tf$placeholder("float", shape(NULL,10))

Loss function : cross-entropy

In [4]:
cross_entropy <- tf$reduce_sum(y_ * tf$log(y))

Optimizer : Gradient Descent (learning_rate = 0.01)

In [5]:
train_step <- tf$train$GradientDescentOptimizer(0.01)$minimize(cross_entropy)

최적화 반복

In [6]:
sess <- tf$Session()
sess$run(tf$global_variables_initializer())
In [7]:
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))))
    }
}
[1] 0.000 0.011
[1] 5.000 0.098
[1] 10.000  0.098
[1] 15.000  0.098
[1] 20.000  0.098
[1] 25.000  0.098
[1] 30.000  0.098
[1] 35.000  0.098
[1] 40.000  0.098
[1] 45.000  0.098
[1] 50.000  0.098
[1] 55.000  0.098
[1] 60.000  0.098
[1] 65.000  0.098
[1] 70.000  0.098
[1] 75.000  0.098
[1] 80.000  0.098
[1] 85.000  0.098
[1] 90.000  0.098
[1] 95.000  0.098
[1] 100.000   0.098

batch size = 100개로 하고, 계속 Gradient Descent를 반복하면서, 5의 배수일 때마다 test set의 정확도를 계산해서 출력한다. 정확도가 기껏해야 0.098로, 성능이 안 좋다는 것을 알 수 있다.