17.1 TensorFlow in R
library(tensorflow)
batch_size <- 128
num_classes <- 10
steps <- 1000
datasets <- tf$contrib$learn$datasets
mnist <- datasets$mnist$read_data_sets("MNIST-data", one_hot = TRUE)
x <- tf$placeholder(tf$float32, shape(NULL, 784L))
W <- tf$Variable(tf$zeros(shape(784L, num_classes)))
b <- tf$Variable(tf$zeros(shape(num_classes)))
y <- tf$nn$softmax(tf$matmul(x, W) + b)
y_ <- tf$placeholder(tf$float32, shape(NULL, num_classes))
cross_entropy <- tf$reduce_mean(-tf$reduce_sum(y_ * log(y), reduction_indices=1L))
train_step <- tf$train$GradientDescentOptimizer(0.5)$minimize(cross_entropy)
sess <- tf$Session()
sess$run(tf$global_variables_initializer())
for (i in 1:steps) {
batches <- mnist$train$next_batch(batch_size)
batch_xs <- batches[[1]]
batch_ys <- batches[[2]]
sess$run(train_step,
feed_dict = dict(x = batch_xs, y_ = batch_ys))
}
correct_prediction <- tf$equal(tf$argmax(y, 1L), tf$argmax(y_, 1L))
accuracy <- tf$reduce_mean(tf$cast(correct_prediction, tf$float32))
score <-sess$run(accuracy,
feed_dict = dict(x = mnist$test$images, y_ = mnist$test$labels))
cat('Test accuracy:', score, '\n')
Test accuracy: 0.9185